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

TOK-512: last cycle rewards timestamps #433

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
9 changes: 9 additions & 0 deletions src/app/collective-rewards/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
fetchBuilderRewardsClaimedLogsByAddress,
fetchGaugeNotifyRewardLogsByAddress,
fetchNotifyRewardLogsByAddress,
fetchRewardDistributionFinishedLogsByAddress,
} from '@/lib/endpoints'

export const fetchNotifyRewardLogs = (fromBlock = 0) => {
Expand Down Expand Up @@ -39,3 +40,11 @@ export const fetchBackerRewardsClaimed = (gaugeAddress: Address, fromBlock = 0)
.replace('{{fromBlock}}', fromBlock.toString()),
)
}

export const fetchRewardDistributionFinished = (fromBlock = 0) => {
return axiosInstance.get(
fetchRewardDistributionFinishedLogsByAddress
.replace('{{address}}', BackersManagerAddress)
.replace('{{fromBlock}}', fromBlock.toString()),
)
}
20 changes: 14 additions & 6 deletions src/app/collective-rewards/rewards/builders/LastCycleRewards.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { useCycleContext } from '@/app/collective-rewards/metrics/context/CycleContext'
import {
formatMetrics,
getLastCycleRewards,
MetricsCard,
MetricsCardTitle,
TokenMetricsCardRow,
useGetGaugeNotifyRewardLogs,
Token,
BuilderRewardDetails,
useGetRewardDistributionFinishedLogs,
getNotifyRewardAmount,
useGetLastCycleRewardsTimestamps,
} from '@/app/collective-rewards/rewards'
import { useHandleErrors } from '@/app/collective-rewards/utils'
import { formatBalanceToHuman } from '@/app/user/Balances/balanceUtils'
Expand All @@ -28,19 +30,25 @@ const TokenRewardsMetrics: FC<TokenRewardsMetricsProps> = ({
currency = 'USD',
}) => {
const { data: cycle, isLoading: cycleLoading, error: cycleError } = useCycleContext()
const {
data: { fromTimestamp, toTimestamp },
isLoading: lastCycleRewardsLoading,
error: lastCycleRewardsError,
} = useGetLastCycleRewardsTimestamps(cycle)

const {
data: rewardsPerToken,
isLoading: logsLoading,
error: rewardsError,
} = useGetGaugeNotifyRewardLogs(gauge)
} = useGetGaugeNotifyRewardLogs(gauge, address, fromTimestamp, toTimestamp)

const error = cycleError ?? rewardsError
const error = cycleError ?? lastCycleRewardsError ?? rewardsError
useHandleErrors({ error, title: 'Error loading last cycle rewards' })

const { prices } = usePricesContext()

const lastCycleRewards = getLastCycleRewards(cycle, rewardsPerToken[address])
const lastCycleRewardsInHuman = Number(formatBalanceToHuman(lastCycleRewards.builderAmount))
const lastCycleRewards = getNotifyRewardAmount(rewardsPerToken, address, 'builderAmount_')
const lastCycleRewardsInHuman = Number(formatBalanceToHuman(lastCycleRewards[address] ?? 0n))
const price = prices[symbol]?.price ?? 0
const { amount, fiatAmount } = formatMetrics(lastCycleRewardsInHuman, price, symbol, currency)

Expand All @@ -50,7 +58,7 @@ const TokenRewardsMetrics: FC<TokenRewardsMetricsProps> = ({
)({
amount,
fiatAmount,
isLoading: cycleLoading || logsLoading,
isLoading: cycleLoading || lastCycleRewardsLoading || logsLoading,
})
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
RbtcSvg,
BuilderRewardPercentage,
TokenRewards,
useGetLastCycleRewardsTimestamps,
} from '@/app/collective-rewards/rewards'
import { formatBalanceToHuman } from '@/app/user/Balances/balanceUtils'
import { usePricesContext } from '@/shared/context/PricesContext'
Expand Down Expand Up @@ -91,31 +92,35 @@ export const useGetBuildersRewards = ({ rif, rbtc }: { [token: string]: Token },
error: rewardsCoinbaseError,
} = useGetRewardsCoinbase()

const { cycleDuration, cycleStart, endDistributionWindow, cycleNext } = cycle
const distributionWindow = endDistributionWindow.diff(cycleStart)
const lastCycleStart = cycleStart.minus({ seconds: cycleDuration.as('seconds') })
const lastCycleAfterDistribution = lastCycleStart.plus({ seconds: distributionWindow.as('seconds') })
const {
data: { fromTimestamp, toTimestamp },
isLoading: lastCycleRewardsLoading,
error: lastCycleRewardsError,
} = useGetLastCycleRewardsTimestamps(cycle)

const {
data: notifyRewardEventLastCycle,
isLoading: logsLoading,
error: logsError,
} = useGetGaugesNotifyReward(
gauges,
undefined,
lastCycleAfterDistribution.toSeconds(),
endDistributionWindow.toSeconds(),
} = useGetGaugesNotifyReward(gauges, undefined, fromTimestamp, toTimestamp)
const rifBuildersRewardsAmount = getNotifyRewardAmount(
notifyRewardEventLastCycle,
rif.address,
'builderAmount_',
)
const rbtcBuildersRewardsAmount = getNotifyRewardAmount(
notifyRewardEventLastCycle,
rbtc.address,
'builderAmount_',
)
const rifBuildersRewardsAmount = getNotifyRewardAmount(notifyRewardEventLastCycle, rif, 'builderAmount_')
const rbtcBuildersRewardsAmount = getNotifyRewardAmount(notifyRewardEventLastCycle, rbtc, 'builderAmount_')

// get the backer reward percentage for each builder we want to show
const buildersAddress = builders.map(({ address }) => address)
const {
data: backersRewardsPct,
isLoading: backersRewardsPctLoading,
error: backersRewardsPctError,
} = useGetBackersRewardPercentage(buildersAddress, cycleNext.toSeconds())
} = useGetBackersRewardPercentage(buildersAddress, cycle.cycleNext.toSeconds())

const isLoading =
rewardSharesLoading ||
Expand All @@ -126,7 +131,8 @@ export const useGetBuildersRewards = ({ rif, rbtc }: { [token: string]: Token },
rewardsERC20Loading ||
rewardsCoinbaseLoading ||
cycleLoading ||
totalPotentialRewardsLoading
totalPotentialRewardsLoading ||
lastCycleRewardsLoading

const error =
rewardSharesError ??
Expand All @@ -137,7 +143,8 @@ export const useGetBuildersRewards = ({ rif, rbtc }: { [token: string]: Token },
rewardsERC20Error ??
rewardsCoinbaseError ??
cycleError ??
totalPotentialRewardsError
totalPotentialRewardsError ??
lastCycleRewardsError

const { prices } = usePricesContext()

Expand Down
2 changes: 2 additions & 0 deletions src/app/collective-rewards/rewards/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,5 @@ export * from './useGetGaugesNotifyReward'
export * from './useGetBackerRewardPercentage'
export * from './useGetBackersRewardPercentage'
export * from './useGetBackerRewardPerTokenPaid'
export * from './useGetRewardDistributionFinishedLogs'
export * from './useGetLastCycleRewardsTimestamps'
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Address, isAddressEqual } from 'viem'
import { useMemo } from 'react'
import { useGetGaugesEvents } from '@/app/collective-rewards/rewards'
import { GaugeNotifyRewardEventLog, useGetGaugesEvents } from '@/app/collective-rewards/rewards'

export const useGetGaugesNotifyReward = (
gauges: Address[],
Expand All @@ -10,21 +10,20 @@ export const useGetGaugesNotifyReward = (
) => {
const { data: eventsData, isLoading, error } = useGetGaugesEvents(gauges, 'NotifyReward')

type Log = GaugeNotifyRewardEventLog[number]
const data = useMemo(() => {
return Object.keys(eventsData).reduce((acc: { [key: string]: (typeof eventsData)[Address] }, key) => {
let events = eventsData[key as Address]
let events = eventsData[key as Address] as (Log & { timeStamp: number })[]
if (rewardToken) {
events = events.filter(event => isAddressEqual(event.args.rewardToken_, rewardToken))
}
if (fromTimestamp) {
events = events.filter(event => {
// @ts-ignore
return event.timeStamp >= fromTimestamp
})
}
if (toTimestamp) {
events = events.filter(event => {
// @ts-ignore
return event.timeStamp <= toTimestamp
})
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { Cycle } from '@/app/collective-rewards/metrics'
import {
RewardDistributionFinishedEventLog,
useGetRewardDistributionFinishedLogs,
} from '@/app/collective-rewards/rewards'

type Log = RewardDistributionFinishedEventLog[number] & { timeStamp: number }
export const useGetLastCycleRewardsTimestamps = ({ cycleStart, cycleDuration, cycleNext }: Cycle) => {
const {
data: rewardDistributionFinished,
isLoading: rewardDistributionFinishedLoading,
error: rewardDistributionFinishedError,
} = useGetRewardDistributionFinishedLogs()

const isLoading = rewardDistributionFinishedLoading
const error = rewardDistributionFinishedError

const lastCycleStart = cycleStart.minus({ seconds: cycleDuration.as('seconds') })
const [penultimateEvent, lastEvent] = rewardDistributionFinished.slice(-2) as Log[]

let fromTimestamp = lastCycleStart.toSeconds()
let toTimestamp = lastCycleStart.toSeconds()

if (penultimateEvent && !lastEvent && penultimateEvent.timeStamp >= cycleStart.toSeconds()) {
toTimestamp = +penultimateEvent.timeStamp
} else if (penultimateEvent && lastEvent) {
if (penultimateEvent.timeStamp >= lastCycleStart.toSeconds()) {
fromTimestamp = +penultimateEvent.timeStamp + 1 // We add 1 second to avoid including the previous cycle
}
if (lastEvent.timeStamp >= cycleStart.toSeconds()) {
toTimestamp = +lastEvent.timeStamp
}
}

return {
data: {
fromTimestamp,
toTimestamp,
},
isLoading,
error,
}
}
54 changes: 42 additions & 12 deletions src/app/collective-rewards/rewards/hooks/useGetNotifyRewardLogs.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { useQuery } from '@tanstack/react-query'
import { fetchGaugeNotifyRewardLogs, fetchNotifyRewardLogs } from '@/app/collective-rewards/actions'
import { Address, getAddress, parseEventLogs } from 'viem'
import { Address, getAddress, isAddressEqual, parseEventLogs } from 'viem'
import { GaugeAbi } from '@/lib/abis/v2/GaugeAbi'
import { BackersManagerAbi } from '@/lib/abis/v2/BackersManagerAbi'
import { BackersManagerAddress } from '@/lib/contracts'
import { AVERAGE_BLOCKTIME } from '@/lib/constants'
import { useMemo } from 'react'

export type NotifyRewardEventLog = ReturnType<
typeof parseEventLogs<typeof BackersManagerAbi, true, 'NotifyReward'>
Expand Down Expand Up @@ -46,28 +47,57 @@ export type GaugeNotifyRewardEventLog = ReturnType<
>
export type GaugeNotifyRewardsPerToken = Record<Address, GaugeNotifyRewardEventLog>

export const useGetGaugeNotifyRewardLogs = (gauge: Address) => {
const { data, error, isLoading } = useQuery({
export const useGetGaugeNotifyRewardLogs = (
gauge: Address,
rewardToken?: Address,
fromTimestamp?: number,
toTimestamp?: number,
) => {
const {
data: events,
error,
isLoading,
} = useQuery({
queryFn: async () => {
const { data } = await fetchGaugeNotifyRewardLogs(gauge)

const events = parseEventLogs({
return parseEventLogs({
abi: GaugeAbi,
logs: data,
eventName: 'NotifyReward',
})

return events.reduce<GaugeNotifyRewardsPerToken>((acc, log) => {
const rewardToken = getAddress(log.args.rewardToken_)
acc[rewardToken] = [...(acc[rewardToken] || []), log]
return acc
}, {})
},
queryKey: ['notifyRewardLogs', gauge],
queryKey: ['notifyRewardLogs', gauge, rewardToken],
refetchInterval: AVERAGE_BLOCKTIME,
initialData: {},
initialData: [],
})

type Log = GaugeNotifyRewardEventLog[number]
const data = useMemo(() => {
return events.reduce<GaugeNotifyRewardsPerToken>((acc, log) => {
const {
timeStamp,
args: { rewardToken_ },
} = log as Log & { timeStamp: number }
const rewardTokenAddress = getAddress(rewardToken_)

if (rewardToken && !isAddressEqual(rewardToken, rewardTokenAddress)) {
return acc
}

if (fromTimestamp && timeStamp < fromTimestamp) {
return acc
}

if (toTimestamp && timeStamp > toTimestamp) {
return acc
}

acc[rewardTokenAddress] = [...(acc[rewardTokenAddress] || []), log]
return acc
}, {})
}, [events, rewardToken, fromTimestamp, toTimestamp])

return {
data,
error,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { useQuery } from '@tanstack/react-query'
import { fetchRewardDistributionFinished } from '@/app/collective-rewards/actions'
import { parseEventLogs } from 'viem'
import { BackersManagerAbi } from '@/lib/abis/v2/BackersManagerAbi'
import { BackersManagerAddress } from '@/lib/contracts'
import { AVERAGE_BLOCKTIME } from '@/lib/constants'

export type RewardDistributionFinishedEventLog = ReturnType<
typeof parseEventLogs<typeof BackersManagerAbi, true, 'RewardDistributionFinished'>
>

export const useGetRewardDistributionFinishedLogs = () => {
const { data, error, isLoading } = useQuery({
queryFn: async () => {
const { data } = await fetchRewardDistributionFinished()

return parseEventLogs({
abi: BackersManagerAbi,
logs: data,
eventName: 'RewardDistributionFinished',
})
},
queryKey: ['RewardDistributionFinished', BackersManagerAddress],
refetchInterval: AVERAGE_BLOCKTIME,
initialData: [],
})

return {
data,
error,
isLoading,
}
}
40 changes: 0 additions & 40 deletions src/app/collective-rewards/rewards/utils/getLastCycleRewards.ts

This file was deleted.

Loading