Skip to content

Commit

Permalink
chore: use cursor in subquery tvl
Browse files Browse the repository at this point in the history
  • Loading branch information
jpangelle committed Feb 22, 2024
1 parent ec7859c commit d90069b
Show file tree
Hide file tree
Showing 4 changed files with 83 additions and 143 deletions.
44 changes: 5 additions & 39 deletions centrifuge-app/src/components/Charts/TotalValueLocked.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import Decimal from 'decimal.js-light'
import * as React from 'react'
import { useQuery } from 'react-query'
import { Area, AreaChart, ResponsiveContainer, Tooltip } from 'recharts'
import { getTinlakeSubgraphTVL } from '../../utils/tinlake/getTinlakeSubgraphTVL'
import { useDailyTVL } from '../../utils/usePools'

export type DataPoint = {
Expand All @@ -17,11 +15,10 @@ type TotalValueLockedProps = {

export default function TotalValueLocked({ chainTVL, setHovered }: TotalValueLockedProps) {
const centrifugeTVL = useDailyTVL()
const tinlakeTVL = useDailyTinlakeTVL()
const chartColor = '#ff8c00'

const chartData = React.useMemo(() => {
if (!tinlakeTVL || !centrifugeTVL) {
if (!centrifugeTVL) {
return []
}

Expand All @@ -32,8 +29,10 @@ export default function TotalValueLocked({ chainTVL, setHovered }: TotalValueLoc
}
: undefined

return getMergedData([...tinlakeTVL, ...centrifugeTVL], currentTVL)
}, [tinlakeTVL, centrifugeTVL, chainTVL])
const tvlSnapshots = centrifugeTVL.map((entry) => ({ ...entry, tvl: entry.tvl.toNumber() }))

return [...tvlSnapshots, currentTVL]
}, [centrifugeTVL, chainTVL])

return (
<ResponsiveContainer>
Expand Down Expand Up @@ -69,36 +68,3 @@ export default function TotalValueLocked({ chainTVL, setHovered }: TotalValueLoc
</ResponsiveContainer>
)
}

function useDailyTinlakeTVL() {
const { data } = useQuery('use daily tinlake tvl', getTinlakeSubgraphTVL, {
staleTime: Infinity,
suspense: true,
})

return data
}

function getMergedData(combined: DataPoint[], current?: DataPoint) {
const mergedMap = new Map()

combined.forEach((entry) => {
const { dateInMilliseconds, tvl } = entry

if (mergedMap.has(dateInMilliseconds)) {
mergedMap.set(dateInMilliseconds, mergedMap.get(dateInMilliseconds).add(tvl))
} else {
mergedMap.set(dateInMilliseconds, tvl)
}
})

if (current) {
mergedMap.set(current.dateInMilliseconds, current.tvl)
}

const merged = Array.from(mergedMap, ([dateInMilliseconds, tvl]) => ({ dateInMilliseconds, tvl }))
.sort((a, b) => a.dateInMilliseconds - b.dateInMilliseconds)
.map((entry) => ({ ...entry, tvl: entry.tvl.toNumber() }))

return merged
}
40 changes: 0 additions & 40 deletions centrifuge-app/src/utils/tinlake/getTinlakeSubgraphTVL.ts

This file was deleted.

136 changes: 72 additions & 64 deletions centrifuge-js/src/modules/pools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2047,13 +2047,17 @@ export function getPoolsModule(inst: Centrifuge) {
)
}

function getPoolSnapshotsWithCursor(poolId: string, endCursor: string | null, from?: Date, to?: Date) {
function getPoolSnapshotsWithCursor(
poolId: string,
endCursor: string | null,
options?: { from?: Date; to?: Date; orderBy?: 'BLOCK_NUMBER_ASC' | 'PERIOD_START_ASC' }
) {
return inst.getSubqueryObservable<{
poolSnapshots: { nodes: SubqueryPoolSnapshot[]; pageInfo: { hasNextPage: boolean; endCursor: string } }
}>(
`query($poolId: String!, $from: Datetime!, $to: Datetime!, $poolCursor: Cursor) {
`query($poolId: String!, $from: Datetime!, $to: Datetime!, $poolCursor: Cursor, $orderBy: [PoolSnapshotsOrderBy!]) {
poolSnapshots(
orderBy: BLOCK_NUMBER_ASC,
orderBy: $orderBy,
filter: {
id: { startsWith: $poolId },
timestamp: { greaterThan: $from, lessThan: $to }
Expand All @@ -2070,6 +2074,12 @@ export function getPoolsModule(inst: Centrifuge) {
sumRepaidAmountByPeriod
sumInvestedAmountByPeriod
sumRedeemedAmountByPeriod
periodStart
pool {
currency {
decimals
}
}
}
pageInfo {
hasNextPage
Expand All @@ -2080,9 +2090,10 @@ export function getPoolsModule(inst: Centrifuge) {
`,
{
poolId,
from: from ? from.toISOString() : getDateYearsFromNow(-10).toISOString(),
to: to ? to.toISOString() : getDateYearsFromNow(10).toISOString(),
from: options?.from ? options.from.toISOString() : getDateYearsFromNow(-10).toISOString(),
to: options?.to ? options.to.toISOString() : getDateYearsFromNow(10).toISOString(),
poolCursor: endCursor,
orderBy: options?.orderBy || null,
}
)
}
Expand Down Expand Up @@ -2134,7 +2145,7 @@ export function getPoolsModule(inst: Centrifuge) {
of({ poolSnapshots: [], endCursor: null, hasNextPage: true }).pipe(
expand(({ poolSnapshots, endCursor, hasNextPage }) => {
if (!hasNextPage) return EMPTY
return getPoolSnapshotsWithCursor(poolId, endCursor, from, to).pipe(
return getPoolSnapshotsWithCursor(poolId, endCursor, { from, to, orderBy: 'BLOCK_NUMBER_ASC' }).pipe(
map(
(
response: {
Expand Down Expand Up @@ -2250,64 +2261,61 @@ export function getPoolsModule(inst: Centrifuge) {
}

function getDailyTVL() {
const $query = inst.getSubqueryObservable<{
poolSnapshots: {
nodes: {
portfolioValuation: string
totalReserve: string
periodStart: string
pool: {
currency: {
decimals: number
}
}
}[]
}
}>(
`query {
poolSnapshots(first: 1000, orderBy: PERIOD_START_ASC) {
nodes {
portfolioValuation
totalReserve
periodStart
pool {
currency {
decimals
return of({ poolSnapshots: [], endCursor: null, hasNextPage: true })
.pipe(
expand(({ poolSnapshots, endCursor, hasNextPage }) => {
if (!hasNextPage) return EMPTY
return getPoolSnapshotsWithCursor('', endCursor, { orderBy: 'PERIOD_START_ASC' }).pipe(
map(
(
response: {
poolSnapshots: {
nodes: SubqueryPoolSnapshot[]
pageInfo: { hasNextPage: boolean; endCursor: string }
}
} | null
) => {
if (response?.poolSnapshots) {
const { endCursor, hasNextPage } = response.poolSnapshots.pageInfo

return {
endCursor,
hasNextPage,
poolSnapshots: [...poolSnapshots, ...response.poolSnapshots.nodes],
}
}
return {}
}
}
)
)
})
)
.pipe(
map(({ poolSnapshots }) => {
if (!poolSnapshots) {
return []
}
}
}`
)

return $query.pipe(
map((data) => {
if (!data) {
return []
}

const mergedMap = new Map()
const formatted = data.poolSnapshots.nodes.map(({ portfolioValuation, totalReserve, periodStart, pool }) => ({
dateInMilliseconds: new Date(periodStart).getTime(),
tvl: new CurrencyBalance(
new BN(portfolioValuation || '0').add(new BN(totalReserve || '0')),
pool.currency.decimals
).toDecimal(),
}))

formatted.forEach((entry) => {
const { dateInMilliseconds, tvl } = entry
const mergedMap = new Map()
const formatted = poolSnapshots.map(({ portfolioValuation, totalReserve, periodStart, pool }) => ({
dateInMilliseconds: new Date(periodStart).getTime(),
tvl: new CurrencyBalance(
new BN(portfolioValuation || '0').add(new BN(totalReserve || '0')),
pool.currency.decimals
).toDecimal(),
}))
formatted.forEach((entry) => {
const { dateInMilliseconds, tvl } = entry

if (mergedMap.has(dateInMilliseconds)) {
mergedMap.set(dateInMilliseconds, mergedMap.get(dateInMilliseconds).add(tvl))
} else {
mergedMap.set(dateInMilliseconds, tvl)
}
if (mergedMap.has(dateInMilliseconds)) {
mergedMap.set(dateInMilliseconds, mergedMap.get(dateInMilliseconds).add(tvl))
} else {
mergedMap.set(dateInMilliseconds, tvl)
}
})
return Array.from(mergedMap, ([dateInMilliseconds, tvl]) => ({ dateInMilliseconds, tvl }))
})

return Array.from(mergedMap, ([dateInMilliseconds, tvl]) => ({ dateInMilliseconds, tvl }))
})
)
)
}

function getDailyTrancheStates(args: [trancheId: string]) {
Expand Down Expand Up @@ -2933,11 +2941,11 @@ export function getPoolsModule(inst: Centrifuge) {
}
> = {}
// oracles.forEach(() => {
// const { timestamp, value } = oracle[1].toPrimitive() as any
// oraclePrices[(oracle[0].toHuman() as any)[0].Isin] = {
// timestamp,
// value: new CurrencyBalance(value, currency.decimals),
// }
// const { timestamp, value } = oracle[1].toPrimitive() as any
// oraclePrices[(oracle[0].toHuman() as any)[0].Isin] = {
// timestamp,
// value: new CurrencyBalance(value, currency.decimals),
// }
// })

const activeLoansPortfolio: Record<
Expand Down
6 changes: 6 additions & 0 deletions centrifuge-js/src/types/subquery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ export type SubqueryPoolSnapshot = {
sumInvestedAmountByPeriod?: number | null
sumRedeemedAmountByPeriod?: number | null
blockNumber: number
periodStart: string
pool: {
currency: {
decimals: number
}
}
}

export type SubqueryTrancheSnapshot = {
Expand Down

0 comments on commit d90069b

Please sign in to comment.