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-525: number formatter #446

Open
wants to merge 8 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
2 changes: 1 addition & 1 deletion .env.testnet.local
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,4 @@ NEXT_PUBLIC_ENABLE_FEATURE_V2_REWARDS=true
# RNS
NEXT_PUBLIC_RNS_REGISTRY_ADDRESS=0x7d284aaac6e925aad802a53c0c69efe3764597b8

NEXT_PUBLIC_NODE_URL=https://public-node.testnet.rsk.co
NEXT_PUBLIC_NODE_URL=https://public-node.testnet.rsk.co
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
'use client'

import { Allocations, AllocationsContext } from '@/app/collective-rewards/allocations/context'
import { formatOnchainFraction } from '@/app/collective-rewards/rewards'
import { Button, ButtonProps } from '@/components/Button'
import { Input } from '@/components/Input'
import { cn } from '@/lib/utils'
import { useContext, useState } from 'react'
import { Address, parseEther } from 'viem'
import { StakeHint } from './StakeHint'
import { formatCurrency } from '@/app/collective-rewards/utils'

const PercentageButton = ({ children, variant, ...rest }: ButtonProps) => (
<Button
Expand Down Expand Up @@ -63,7 +63,7 @@ export const AllocationAmount = () => {
name="allocated-amount"
fullWidth
onChange={handleOnChange}
value={formatOnchainFraction(amountToAllocate)}
value={formatCurrency(amountToAllocate, 'stRIF')}
errorMessage={
cumulativeAllocation > amountToAllocate && cumulativeAllocation < balance
? ALLOCATION_EXCEED_AMOUNT_ERROR
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use client'

import { AllocationsContext } from '@/app/collective-rewards/allocations/context'
import { formatOnchainFraction } from '@/app/collective-rewards/rewards'
import { formatCurrency } from '@/app/collective-rewards/utils'
import { Paragraph } from '@/components/Typography'
import { useContext } from 'react'

Expand Down Expand Up @@ -45,11 +45,11 @@ export const AllocationMetrics = () => {
},
} = useContext(AllocationsContext)

const balanceValue = `${formatOnchainFraction(balance)} stRIF`
const balanceValue = `${formatCurrency(balance, 'stRIF')} stRIF`

const allocatedAmountValue = `${formatOnchainFraction(amountToAllocate)} stRIF`
const allocatedAmountValue = `${formatCurrency(amountToAllocate, 'stRIF')} stRIF`

const unallocatedAmount = formatOnchainFraction(balance - amountToAllocate)
const unallocatedAmount = formatCurrency(balance - amountToAllocate, 'stRIF')

const unallocatedAmountValue = `${unallocatedAmount} stRIF`
return (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AllocationsContext } from '@/app/collective-rewards/allocations/context'
import { formatOnchainFraction } from '@/app/collective-rewards/rewards'
import { formatCurrency } from '@/app/collective-rewards/utils'
import { weiToPercentage } from '@/app/collective-rewards/settings'
import { Builder } from '@/app/collective-rewards/types'
import { Input } from '@/components/Input'
Expand Down Expand Up @@ -41,9 +41,9 @@ export const BuilderAllocation = (builder: BuilderAllocationProps) => {
<Input
type="number"
name={`allocation-${address}`}
hint={`Allocation left ${allocationLeft > 0 ? formatOnchainFraction(allocationLeft) : '0'} stRIF`}
hint={`Allocation left ${allocationLeft > 0 ? formatCurrency(allocationLeft, 'stRIF') : '0'} stRIF`}
onChange={onInputChange}
value={formatOnchainFraction(currentAllocation || 0n)}
value={formatCurrency(currentAllocation || 0n, 'stRIF')}
/>
<Slider
value={[Number(currentAllocation || 0n)]}
Expand Down
4 changes: 1 addition & 3 deletions src/app/collective-rewards/metrics/AllTimeRewardsMetrics.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
import { FC } from 'react'
import { useHandleErrors } from '@/app/collective-rewards/utils'
import { withSpinner } from '@/components/LoadingSpinner/withLoadingSpinner'
import { formatBalanceToHuman } from '@/app/user/Balances/balanceUtils'
import { usePricesContext } from '@/shared/context/PricesContext'

type TokenRewardsMetricsProps = {
Expand Down Expand Up @@ -40,10 +39,9 @@ const TokenRewardsMetrics: FC<TokenRewardsMetricsProps> = ({
0n,
)

const totalRewardsInHuman = Number(formatBalanceToHuman(totalRewards))
const price = prices[symbol]?.price ?? 0

const { amount, fiatAmount } = formatMetrics(totalRewardsInHuman, price, symbol, currency)
const { amount, fiatAmount } = formatMetrics(totalRewards, price, symbol, currency)

return withSpinner(
TokenMetricsCardRow,
Expand Down
11 changes: 5 additions & 6 deletions src/app/collective-rewards/metrics/TotalAllocationsMetrics.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,15 @@ import { useGaugesGetFunction } from '@/app/collective-rewards/shared/hooks'
import { Address } from 'viem'
import { FC } from 'react'
import { usePricesContext } from '@/shared/context/PricesContext'
import { formatCurrency } from '@/lib/utils'
import {
MetricsCard,
MetricsCardTitle,
TokenMetricsCardRow,
Token,
formatOnchainFraction,
formatMetrics,
} from '@/app/collective-rewards/rewards'
import { withSpinner } from '@/components/LoadingSpinner/withLoadingSpinner'
import { useHandleErrors } from '@/app/collective-rewards/utils'
import { useHandleErrors, formatCurrency } from '@/app/collective-rewards/utils'

type TotalAllocationsProps = {
gauges: Address[]
Expand All @@ -31,8 +30,8 @@ export const TotalAllocationsMetrics: FC<TotalAllocationsProps> = ({
const price = prices[symbol]?.price ?? 0

const totalAllocations = Object.values(data).reduce((acc, allocation) => acc + allocation, 0n)
const totalAllocationsInHuman = Number(formatOnchainFraction(totalAllocations))
const fiatAmount = `= ${currency} ${formatCurrency(totalAllocationsInHuman * price, currency)}`

const { amount, fiatAmount } = formatMetrics(totalAllocations, price, 'stRIF', currency)

return (
<MetricsCard borderless>
Expand All @@ -47,7 +46,7 @@ export const TotalAllocationsMetrics: FC<TotalAllocationsProps> = ({
TokenMetricsCardRow,
'min-h-0 grow-0',
)({
amount: `${totalAllocationsInHuman} STRIF`,
amount,
fiatAmount,
isLoading,
})}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
useBackerRewardsContext,
ClaimYourRewardsButton,
} from '@/app/collective-rewards/rewards'
import { formatBalanceToHuman } from '@/app/user/Balances/balanceUtils'
import { useHandleErrors } from '@/app/collective-rewards/utils'
import { withSpinner } from '@/components/LoadingSpinner/withLoadingSpinner'

Expand All @@ -35,12 +34,7 @@ const TokenRewardsMetrics: FC<TokenRewardsMetricsProps> = ({

const tokenPrice = prices[symbol]?.price ?? 0

const { amount, fiatAmount } = formatMetrics(
Number(formatBalanceToHuman(earnedRewards)),
tokenPrice,
symbol,
currency,
)
const { amount, fiatAmount } = formatMetrics(earnedRewards, tokenPrice, symbol, currency)

const { claimRewards, isClaimable } = useClaimBackerRewards(address)

Expand Down
4 changes: 1 addition & 3 deletions src/app/collective-rewards/rewards/backers/RewardsCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
TooltipProps,
} from '@/app/collective-rewards/rewards'
import { useHandleErrors } from '@/app/collective-rewards/utils'
import { formatBalanceToHuman } from '@/app/user/Balances/balanceUtils'
import { usePricesContext } from '@/shared/context/PricesContext'
import { FC } from 'react'
import { withSpinner } from '@/components/LoadingSpinner/withLoadingSpinner'
Expand Down Expand Up @@ -46,10 +45,9 @@ const TokenRewardsMetrics: FC<TokenRewardsMetricsProps> = ({

const { prices } = usePricesContext()

const totalRewardsInHuman = Number(formatBalanceToHuman(totalRewards))
const price = prices[symbol]?.price ?? 0

const { amount, fiatAmount } = formatMetrics(totalRewardsInHuman, price, symbol, currency)
const { amount, fiatAmount } = formatMetrics(totalRewards, price, symbol, currency)

return withSpinner(
TokenMetricsCardRow,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
import {
formatMetrics,
MetricsCard,
MetricsCardTitle,
TokenMetricsCardRow,
useGetBuilderRewards,
useGetBuilderRewardsClaimedLogs,
Token,
BuilderRewardDetails,
formatMetrics,
} from '@/app/collective-rewards/rewards'
import { useHandleErrors } from '@/app/collective-rewards/utils'
import { formatBalanceToHuman } from '@/app/user/Balances/balanceUtils'
import { withSpinner } from '@/components/LoadingSpinner/withLoadingSpinner'
import { usePricesContext } from '@/shared/context/PricesContext'
import { FC } from 'react'
Expand Down Expand Up @@ -49,10 +48,9 @@ const TokenRewardsMetrics: FC<TokenRewardsMetricsProps> = ({
}, 0n) ?? 0n

const totalRewards = totalClaimedRewards + (claimableRewards ?? 0n)
const totalRewardsInHuman = Number(formatBalanceToHuman(totalRewards))
const price = prices[symbol]?.price ?? 0

const { amount, fiatAmount } = formatMetrics(totalRewardsInHuman, price, symbol, currency)
const { amount, fiatAmount } = formatMetrics(totalRewards, price, symbol, currency)

return withSpinner(
TokenMetricsCardRow,
Expand Down
10 changes: 2 additions & 8 deletions src/app/collective-rewards/rewards/builders/ClaimableRewards.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import {
formatMetrics,
MetricsCard,
MetricsCardTitle,
TokenMetricsCardRow,
Expand All @@ -8,9 +7,9 @@ import {
Token,
ClaimYourRewardsButton,
BuilderRewardDetails,
formatMetrics,
} from '@/app/collective-rewards/rewards'
import { useHandleErrors } from '@/app/collective-rewards/utils'
import { formatBalanceToHuman } from '@/app/user/Balances/balanceUtils'
import { withSpinner } from '@/components/LoadingSpinner/withLoadingSpinner'
import { usePricesContext } from '@/shared/context/PricesContext'
import { FC } from 'react'
Expand Down Expand Up @@ -40,12 +39,7 @@ const TokenRewardsMetrics: FC<TokenRewardsMetricsProps> = ({

const tokenPrice = prices[symbol]?.price ?? 0

const { amount, fiatAmount } = formatMetrics(
Number(formatBalanceToHuman(rewards ?? 0n)),
tokenPrice,
symbol,
currency,
)
const { amount, fiatAmount } = formatMetrics(rewards ?? 0n, tokenPrice, symbol, currency)

const { isClaimable, claimRewards, isPaused } = useClaimBuilderRewardsPerToken(builder, gauge, address)
const content = isPaused ? 'You cannot be paused to claim rewards' : undefined
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
useGetBackerRewardPercentage,
} from '@/app/collective-rewards/rewards'
import { useHandleErrors } from '@/app/collective-rewards/utils'
import { formatBalanceToHuman } from '@/app/user/Balances/balanceUtils'
import { usePricesContext } from '@/shared/context/PricesContext'
import { FC, useEffect, useState } from 'react'
import { Address } from 'viem'
Expand Down Expand Up @@ -75,10 +74,9 @@ const TokenRewards: FC<TokenRewardsProps> = ({ builder, gauge, token: { id, symb
const rewardsAmount =
rewardShares && totalPotentialRewards ? (rewards * rewardShares) / totalPotentialRewards : 0n
// The complement of the reward percentage is applied to the estimated rewards since are from the builder's perspective
const estimatedRewardsInHuman =
Number(formatBalanceToHuman(rewardsAmount)) * (1 - rewardPercentageToApply / 100)
const estimatedRewards = BigInt(rewardsAmount) * (1n - BigInt(rewardPercentageToApply) / 100n)
const price = prices[symbol]?.price ?? 0
const { amount, fiatAmount } = formatMetrics(estimatedRewardsInHuman, price, symbol, currency)
const { amount, fiatAmount } = formatMetrics(estimatedRewards, price, symbol, currency)

return withSpinner(
TokenMetricsCardRow,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
BuilderRewardDetails,
} from '@/app/collective-rewards/rewards'
import { useHandleErrors } from '@/app/collective-rewards/utils'
import { formatBalanceToHuman } from '@/app/user/Balances/balanceUtils'
import { withSpinner } from '@/components/LoadingSpinner/withLoadingSpinner'
import { usePricesContext } from '@/shared/context/PricesContext'
import { FC } from 'react'
Expand Down Expand Up @@ -39,10 +38,9 @@ const TokenRewardsMetrics: FC<TokenRewardsMetricsProps> = ({

const { prices } = usePricesContext()

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

return withSpinner(
TokenMetricsCardRow,
Expand Down
85 changes: 38 additions & 47 deletions src/app/collective-rewards/rewards/utils/formatMetrics.test.ts
Original file line number Diff line number Diff line change
@@ -1,64 +1,55 @@
import { describe, it, expect } from 'vitest'
import { formatMetrics, formatOnchainFraction } from './formatMetrics'
import { describe, it, expect, test } from 'vitest'
import { formatMetrics } from './formatMetrics'
import { formatUnits, parseEther } from 'viem'

describe('formatOnchainFraction', () => {
it('should format onchain fraction correctly with default decimals', () => {
const amount = BigInt('1000000000000000000')
const result = formatOnchainFraction(amount)
expect(result).toBe('1')
})
const formatFiatAmount = (amount: number, currency: string) => `= ${currency} ${amount}`

it('should format onchain fraction correctly with custom display decimals', () => {
const amount = BigInt('1234567890000000000')
const result = formatOnchainFraction(amount, 3)
expect(result).toBe('1.234')
})
const formatAmount = (amount: number, symbol: string) => `${amount} ${symbol}`

it('should round to the lower number', () => {
const amount = BigInt('1237567890000000000')
const result = formatOnchainFraction(amount, 2)
expect(result).toBe('1.23')
})
describe('formatMetrics', () => {
it('should return `fiatAmount` equals to 0 if `amount` is zero', () => {
const result = formatMetrics(0, 10, 'RIF', 'USD')

it('should format onchain fraction correctly with custom decimals', () => {
const amount = BigInt('123456789')
const result = formatOnchainFraction(amount, 2, 9)
expect(result).toBe('0.12')
expect(result.fiatAmount).toBe(formatFiatAmount(0, 'USD'))
})
it('should return `fiatAmount` equals to 0 if `price` is zero', () => {
const result = formatMetrics(10, 0, 'RIF', 'USD')

it('should handle zero amount correctly', () => {
const amount = BigInt('0')
const result = formatOnchainFraction(amount)
expect(result).toBe('0')
expect(result.fiatAmount).toBe(formatFiatAmount(0, 'USD'))
})
it('should return `amount` equals to 0 if `amount` is zero ', () => {
const result = formatMetrics(0, 10, 'RIF', 'USD')

it('should handle numbers without decimals', () => {
const amount = BigInt('9000000000000000000')
const result = formatOnchainFraction(amount)
expect(result).toBe('9')
expect(result.amount).toBe(formatAmount(0, 'RIF'))
})
it('should accept value as different data types(amount)', () => {
const valueAsNumber = 1.23456789
const valueAsBigInt = 1234567890000000000n

it('should handle numbers without decimals and more than 1 character', () => {
const amount = BigInt('90000000000000000000')
const result = formatOnchainFraction(amount)
expect(result).toBe('90')
})
const resultBigInt = formatMetrics(valueAsBigInt, 10, 'RIF', 'USD')
const resultNumber = formatMetrics(valueAsNumber, 10, 'RIF', 'USD')

it('should handle numbers with decimals and 3 characters', () => {
const amount = BigInt('900561000000000000000')
const result = formatOnchainFraction(amount)
expect(result).toBe('900.56')
expect(resultBigInt.amount).toBe(formatAmount(1.23, 'RIF'))
expect(resultBigInt.fiatAmount).toBe(formatFiatAmount(12.346, 'USD'))
expect(resultNumber.amount).toBe(formatAmount(1.23, 'RIF'))
expect(resultNumber.fiatAmount).toBe(formatFiatAmount(12.346, 'USD'))
})
it('should accept value as different data types(price)', () => {
const resultBigInt = formatMetrics(1.23456789, 10n, 'RIF', 'USD')
const resultNumber = formatMetrics(1.23456789, 10, 'RIF', 'USD')

it('should handle numbers with decimals and 3 characters', () => {
const amount = BigInt('9000127000000000000000')
const result = formatOnchainFraction(amount)
expect(result).toBe('9000.12')
expect(resultBigInt.amount).toBe(formatAmount(1.23, 'RIF'))
expect(resultBigInt.fiatAmount).toBe(formatFiatAmount(12.346, 'USD'))
expect(resultNumber.amount).toBe(formatAmount(1.23, 'RIF'))
expect(resultNumber.fiatAmount).toBe(formatFiatAmount(12.346, 'USD'))
})
it.only('should format RIF properly', () => {
const result = formatMetrics(parseEther('10'), 10, 'RIF', 'USD')
Copy link
Contributor

@franciscotobar franciscotobar Dec 10, 2024

Choose a reason for hiding this comment

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

I started with the creation of the tests, but I found out the following challenge that we may need to change or not.

If I do formatCurrency(10,USD) it returns 0.

If I want to represent a 10 I need to do formatCurrency(10.000000000000000000,USD) or formatCurrency(10000000000000000000,USD).

Im not sure if this is the way that it should work but its confusing.


it('should handle very big numbers', () => {
const amount = BigInt('987654321123456789012300000000000000')
const result = formatOnchainFraction(amount)
expect(result).toBe('987654321123456789.01')
expect(result.amount).toBe(formatAmount(10, 'RIF'))
expect(result.fiatAmount).toBe(formatFiatAmount(100, 'USD'))
})
it('should format RBTC properly', () => {})
it('should apply format properly', () => {})
it('should format currency properly', () => {})
})
Loading
Loading