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 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
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,163 @@
import {
useGetRewardDistributionFinishedLogs,
useGetLastCycleRewardsTimestamps,
RewardDistributionFinishedEventLog,
} from '@/app/collective-rewards/rewards'
import { describe, expect, it, vi } from 'vitest'
import { Cycle } from '@/app/collective-rewards/metrics'
import { DateTime, Duration } from 'luxon'

vi.mock('@/app/collective-rewards/rewards/hooks/useGetRewardDistributionFinishedLogs', () => {
return {
useGetRewardDistributionFinishedLogs: vi.fn(),
}
})

describe('useGetLastCycleRewardsTimestamps', () => {
type Log = RewardDistributionFinishedEventLog[number] & { timeStamp: number }
const startTimestamp = 1733011200 // 2024-12-01 00:00:00
const duration = 1209600 // 14 days
const distributionWindow = 3600 // 1 hour
const cycle: Cycle = {
cycleStart: DateTime.fromSeconds(startTimestamp),
cycleNext: DateTime.fromSeconds(startTimestamp + duration),
cycleDuration: Duration.fromObject({ seconds: duration }),
fistCycleStart: DateTime.fromSeconds(startTimestamp),
endDistributionWindow: DateTime.fromSeconds(distributionWindow),
}
const { cycleStart, cycleDuration } = cycle
const lastCycleStart = cycle.cycleStart.minus({ seconds: cycleDuration.as('seconds') })

it('should return a 0 time difference when there are no distributions', () => {
vi.mocked(useGetRewardDistributionFinishedLogs).mockImplementation(() => {
return {
data: [],
isLoading: false,
error: null,
}
})

const { data } = useGetLastCycleRewardsTimestamps(cycle)

expect(data).toEqual({
fromTimestamp: lastCycleStart.toSeconds(),
toTimestamp: lastCycleStart.toSeconds(),
})
})

it('should return a 0 time difference when there is only one distribution and happened in the previous cycle', () => {
vi.mocked(useGetRewardDistributionFinishedLogs).mockImplementation(() => {
return {
data: [
{
timeStamp: lastCycleStart.toSeconds(),
},
] as Log[],
isLoading: false,
error: null,
}
})

const { data } = useGetLastCycleRewardsTimestamps(cycle)

expect(data).toEqual({
fromTimestamp: lastCycleStart.toSeconds(),
toTimestamp: lastCycleStart.toSeconds(),
})
})

it('should return from the last cycle start to cycle start when there is only one distribution and did not happen in this cycle', () => {
vi.mocked(useGetRewardDistributionFinishedLogs).mockImplementation(() => {
return {
data: [
{
timeStamp: cycleStart.toSeconds(),
},
] as Log[],
isLoading: false,
error: null,
}
})

const { data } = useGetLastCycleRewardsTimestamps(cycle)

expect(data).toEqual({
fromTimestamp: lastCycleStart.toSeconds(),
toTimestamp: cycleStart.toSeconds(),
})
})

it('should return a 0 time difference when there is no distribution in this cycle', () => {
const beforeLastCycleStart = lastCycleStart.minus({ seconds: cycleDuration.as('seconds') })
vi.mocked(useGetRewardDistributionFinishedLogs).mockImplementation(() => {
return {
data: [
{
timeStamp: beforeLastCycleStart.toSeconds(),
},
{
timeStamp: lastCycleStart.toSeconds(),
},
] as Log[],
isLoading: false,
error: null,
}
})

const { data } = useGetLastCycleRewardsTimestamps(cycle)

expect(data).toEqual({
fromTimestamp: lastCycleStart.toSeconds(),
toTimestamp: lastCycleStart.toSeconds(),
})
})

it('should return from the (last cycle start + 1) to cycle start when there are 2 consecutive distributions and one was in this cycle', () => {
vi.mocked(useGetRewardDistributionFinishedLogs).mockImplementation(() => {
return {
data: [
{
timeStamp: lastCycleStart.toSeconds(),
},
{
timeStamp: cycleStart.toSeconds(),
},
] as Log[],
isLoading: false,
error: null,
}
})

const { data } = useGetLastCycleRewardsTimestamps(cycle)

expect(data).toEqual({
fromTimestamp: lastCycleStart.toSeconds() + 1,
toTimestamp: cycleStart.toSeconds(),
})
})

it('should return from the last cycle start to cycle start when there are 2 distributions and one was in this cycle', () => {
const beforeLastCycleStart = lastCycleStart.minus({ seconds: cycleDuration.as('seconds') })
vi.mocked(useGetRewardDistributionFinishedLogs).mockImplementation(() => {
return {
data: [
{
timeStamp: beforeLastCycleStart.toSeconds(),
},
{
timeStamp: cycleStart.toSeconds(),
},
] as Log[],
isLoading: false,
error: null,
}
})

const { data } = useGetLastCycleRewardsTimestamps(cycle)

expect(data).toEqual({
fromTimestamp: lastCycleStart.toSeconds(),
toTimestamp: cycleStart.toSeconds(),
})
})
})
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 }: 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,
}
}
Loading
Loading