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

refactor: query validators uptime on demand [PTD-1313] #988

Merged
merged 6 commits into from
Oct 15, 2024
Merged
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
4 changes: 2 additions & 2 deletions apps/dashboard/sonar-project.properties
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ sonar.organization=radixdlt-github
sonar.projectKey=radixdlt_dashboard

sonar.sources=src
sonar.coverage.exclusions=**/*.test.*
sonar.coverage.exclusions=**/*.test.*,**/*.spec.*
#sonar.tests=src
sonar.javascript.lcov.reportPaths=coverage/storybook/lcov.info
sonar.javascript.lcov.reportPaths=coverage/lcov.info
27 changes: 27 additions & 0 deletions apps/dashboard/src/lib/validators/UptimeSelector.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<script lang="ts">
import {
uptimeUiOptions as options,
type UptimeValue
} from '@api/utils/entities/component/validator'
import SimplePicker from '@components/_base/picker/simple-picker/SimplePicker.svelte'
import { uptimeModule } from './uptime-module'

export let selected: UptimeValue

let selectedValue: (typeof options)[number]
$: selected = selectedValue?.value
$: {
uptimeModule.maybeQueryUptime(selected)
}
</script>

<div class="picker">
<SimplePicker {options} bind:selected={selectedValue} />
</div>

<style lang="scss">
.picker {
width: var(--uptime-selector-width, 6rem);
min-width: 6rem;
}
</style>
112 changes: 112 additions & 0 deletions apps/dashboard/src/lib/validators/uptime-module.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import type { ValidatorCollectionItem } from '@common/gateway-sdk'
import { UptimeModule } from './uptime-module'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import BigNumber from 'bignumber.js'
import { ok } from 'neverthrow'

describe('uptime module', () => {
let uptimeModule: UptimeModule
let getUptimeFromDateSpy = vi.fn()
let getValidatorsUptimeSpy = vi.fn().mockReturnValue(getUptimeFromDateSpy)

beforeEach(() => {
uptimeModule = UptimeModule({
getValidatorUptimeSinceDate: getValidatorsUptimeSpy
})
})

describe('initial state, without validators set', () => {
it('should do nothing when called without uptime', () => {
const result = uptimeModule.maybeQueryUptime(undefined)
expect(getValidatorsUptimeSpy).not.toHaveBeenCalled()
expect(result).toBeUndefined()
})

it('should throw when trying to query uptime', () => {
expect(() => uptimeModule.maybeQueryUptime('1month')).toThrowError(
/Validators not set/
)
})

it('should return empty object when getting data', () => {
expect(uptimeModule.getDataForUptime('1month')).toEqual({})
})

it('should throw when trying to get APY', () => {
expect(() =>
uptimeModule.getApy({} as ValidatorCollectionItem, '1month')
).toThrowError(/Invalid totalAmountStaked/)
})
})

describe('with validators', () => {
beforeEach(() => {
uptimeModule.setValidators(
Promise.resolve([
{ address: '1', totalStakeInXRD: new BigNumber(1) },
{ address: '2', totalStakeInXRD: new BigNumber(2) }
])
)
})

it('should not throw when getting APY', () => {
expect(() =>
uptimeModule.getApy(
{
address: '1',
effective_fee_factor: { current: { fee_factor: '0' } }
} as unknown as ValidatorCollectionItem,
'1month'
)
).not.toThrow()
})

describe('with `maybeQueryUptime` called', () => {
let data: any
beforeEach(async () => {
getUptimeFromDateSpy.mockResolvedValueOnce(
ok({
'1': 0.5,
'2': 0.75
})
)

data = await uptimeModule.maybeQueryUptime('1month')
})

it('should call getValidatorUptimeSinceDate', () => {
expect(getUptimeFromDateSpy).toHaveBeenCalled()
expect(data.value).toEqual({
'1': 0.5,
'2': 0.75
})
})

it('should calculate APY correctly', async () => {
const apy = uptimeModule.getApy(
{
address: '1',
effective_fee_factor: { current: { fee_factor: '0.5' } }
} as unknown as ValidatorCollectionItem,
'1month'
)
expect(apy).toBe(25000000)
})

it('should return data from cache if possible', () => {
const data = uptimeModule.maybeQueryUptime('1month')
expect(data).toEqual({
'1': 0.5,
'2': 0.75
})
})

it('should clean data correctly', () => {
uptimeModule.clean()
expect(() => uptimeModule.maybeQueryUptime('1month')).toThrowError(
/Validators not set/
)
})
})
})
})
115 changes: 115 additions & 0 deletions apps/dashboard/src/lib/validators/uptime-module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { ResultAsync } from 'neverthrow'
import { BehaviorSubject } from 'rxjs'
import {
getValidatorUptimeSinceDate as getValidatorUptimeSinceDateOriginal,
uptimePeriodDefinition,
type UptimeValue
} from '@api/utils/entities/component/validator'
import BigNumber from 'bignumber.js'
import type { ValidatorCollectionItem } from '@common/gateway-sdk'
import { YEARLY_XRD_EMISSIONS } from '@constants'
import { writable } from 'svelte/store'

/**
* Uptime Data is an object which contains validator->uptime mapping for a specific uptime period.
*
* Example of Uptime Data:
* {
* '1day': {
* 'validator_xyz': 0.99,
* 'validator_xxx': 0.54,
* },
* '1month': {
* 'validator_abc': 0.99,
* 'validator_bcd': 0.54,
* },
* }
*/
export type UptimeData = Partial<
Record<UptimeValue, Record<string, number | undefined>>
>

export type UptimeModule = ReturnType<typeof UptimeModule>
export const UptimeModule = (
dependencies: {
getValidatorUptimeSinceDate: typeof getValidatorUptimeSinceDateOriginal
} = {
getValidatorUptimeSinceDate: getValidatorUptimeSinceDateOriginal
}
) => {
const { getValidatorUptimeSinceDate } = dependencies
const isLoading = writable<boolean>(false)
const lastQueriedUptime = writable<UptimeValue>('1month')
let validators:
| Promise<{ address: string; totalStakeInXRD: BigNumber }[]>
| undefined
let uptimeData: UptimeData = {}
let totalAmountStaked: BigNumber | undefined
return {
setValidators: (
promise: Promise<{ address: string; totalStakeInXRD: BigNumber }[]>
) => {
validators = promise
promise.then((v) => {
totalAmountStaked = v.reduce(
(prev, cur) => prev.plus(cur.totalStakeInXRD),
new BigNumber(0)
)
})
},
getDataForUptime: (uptime: UptimeValue) => uptimeData[uptime] || {},
getApy: (validator: ValidatorCollectionItem, uptime: UptimeValue) => {
if (!totalAmountStaked || totalAmountStaked.isZero()) {
throw new Error('Invalid totalAmountStaked')
dawidsowardx marked this conversation as resolved.
Show resolved Hide resolved
}
const address = validator.address
const fee = Number(validator.effective_fee_factor?.current?.fee_factor)
const uptimePercentage = uptimeData[uptime]?.[address]

return new BigNumber(YEARLY_XRD_EMISSIONS)
.multipliedBy((1 - fee) * (uptimePercentage ?? 0))
.dividedBy(totalAmountStaked)
.toNumber()
},
maybeQueryUptime: (uptime: UptimeValue | undefined) => {
if (!uptime) return
if (!validators) {
dawidsowardx marked this conversation as resolved.
Show resolved Hide resolved
throw new Error('Validators not set. Call `setValidators` first.')
}
lastQueriedUptime.set(uptime)
if (uptimeData[uptime]) {
return uptimeData[uptime]
}

uptimeData[uptime] = {}

isLoading.set(true)

return ResultAsync.fromPromise(validators, (e) => e)
.andThen((v) =>
getValidatorUptimeSinceDate(v.map((v) => v.address))(
uptimePeriodDefinition[uptime].getStartingPoint()
)
)
.map((value) => {
uptimeData[uptime] = value
isLoading.set(false)
return uptimeData[uptime]
})
.mapErr((e) => {
uptimeData[uptime] = undefined
isLoading.set(false)
return e
})
},
clean: () => {
validators = undefined
uptimeData = {}
totalAmountStaked = undefined
},
isLoading,
lastQueriedUptime
}
}

export const uptimeModule = UptimeModule()
dawidsowardx marked this conversation as resolved.
Show resolved Hide resolved
Loading
Loading