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

Fix of UI Rounding error on staking/unstaking amounts #262

Merged
merged 4 commits into from
Oct 10, 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
2,253 changes: 2,006 additions & 247 deletions package-lock.json

Large diffs are not rendered by default.

11 changes: 9 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build",
"e2e-open": "start-server-and-test dev http://localhost:3000 \"cypress open --e2e\"",
"e2e-test": "start-server-and-test dev http://localhost:3000 \"cypress run --e2e\""
"e2e-test": "start-server-and-test dev http://localhost:3000 \"cypress run --e2e\"",
"test": "vitest"
},
"dependencies": {
"@hookform/resolvers": "^3.7.0",
Expand All @@ -24,6 +25,7 @@
"axios": "^1.7.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
"decimal.js": "^10.4.3",
"ethers": "^6.13.1",
"jdenticon": "^3.3.0",
"lottie-react": "^2.4.0",
Expand Down Expand Up @@ -51,22 +53,27 @@
"@storybook/nextjs": "^8.1.10",
"@storybook/react": "^8.1.10",
"@storybook/test": "^8.1.10",
"@testing-library/jest-dom": "^6.5.0",
"@testing-library/react": "^16.0.1",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"@vitejs/plugin-react": "^4.3.2",
"cypress": "^13.11.0",
"encoding": "^0.1.13",
"eslint": "^8",
"eslint-config-next": "14.2.3",
"eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-storybook": "^0.8.0",
"jsdom": "^25.0.1",
"pino-pretty": "^11.2.1",
"postcss": "^8",
"prettier": "^3.3.2",
"start-server-and-test": "^2.0.4",
"storybook": "^8.1.10",
"tailwindcss": "^3.4.1",
"typescript": "^5"
"typescript": "^5",
"vitest": "^2.1.2"
},
"engines": {
"node": ">=18.0.0"
Expand Down
66 changes: 66 additions & 0 deletions src/app/user/Stake/StakingContext.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { expect, describe, it, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { StakingProvider, useStakingContext } from './StakingContext'
import { StakingToken } from './types'

const TestComponent = ({ stakeAmount, id }: { stakeAmount: string; id: number }) => {
const { amountDataToReceive, onAmountChange } = useStakingContext()
return (
<div>
<span data-testid={`amountToReceive-${id}`}>{amountDataToReceive.amountToReceive}</span>
<span data-testid={`amountToReceiveConvertedToCurrency-${id}`}>
{amountDataToReceive.amountToReceiveConvertedToCurrency}
</span>
<button data-testid={`setAmountButton-${id}`} onClick={() => onAmountChange(stakeAmount)}>
Set Amount
</button>
</div>
)
}
const actionToUse = vi.fn()
actionToUse.mockClear()
const rif: Omit<StakingToken, 'price'> = {
balance: '294.0',
symbol: 'tRIF',
contract: '0x19f64674d8a5b4e652319f5e239efd3bc969a1fe',
}
const stRif: Omit<StakingToken, 'price'> = {
balance: '13.0',
symbol: 'stRIF',
contract: '0xC4b091d97AD25ceA5922f09fe80711B7ACBbb16f',
}
const actionName = 'STAKE'

describe('StakingProvider', () => {
it('Amount to receive is a whole number if the stake amount is also a whole number and the token prices are equal', () => {
let allTestsPass = true

// running the test 500 times with different stake amounts and token prices
for (let i = 0; i < 500; i++) {
// stake amount is a whole number
const stakeAmount = i.toString()
// StRif and Rif prices are equal
const price = Math.random().toString()
render(
<StakingProvider
tokenToSend={{ ...rif, price }}
tokenToReceive={{ ...stRif, price }}
actionToUse={actionToUse}
actionName={actionName}
>
<TestComponent stakeAmount={stakeAmount} id={i} />
</StakingProvider>,
)

fireEvent.click(screen.getByTestId(`setAmountButton-${i}`))
const amountToReceive = screen.getByTestId(`amountToReceive-${i}`)
// if amount to receive is not a whole number
// or if the amount to receive is not equal to the stake amount
if (amountToReceive.textContent?.includes('.') || stakeAmount !== amountToReceive.textContent) {
allTestsPass = false
break
}
}
expect(allTestsPass).toBe(true)
})
})
19 changes: 14 additions & 5 deletions src/app/user/Stake/StakingContext.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createContext, FC, ReactNode, useCallback, useContext, useMemo, useState } from 'react'
import Decimal from 'decimal.js'
import { useBalancesContext } from '@/app/user/Balances/context/BalancesContext'
import { GetPricesResult, TokenBalanceRecord } from '@/app/user/types'
import { StakingToken } from '@/app/user/Stake/types'
Expand Down Expand Up @@ -106,20 +107,28 @@ export const StakingProvider: FC<Props> = ({
const [stakeTxHash, setStakeTxHash] = useState('')

const amountDataToReceive = useMemo(() => {
const amountToReceive =
(Number(stakeData.amount) * Number(tokenToSend.price)) / Number(tokenToReceive.price)
const amountToReceiveConvertedToCurrency = amountToReceive * Number(tokenToReceive.price) || 0
const receiveTokenPrice = new Decimal(tokenToReceive.price || 0)
const sendTokenPrice = new Decimal(tokenToSend.price || 0)
if (receiveTokenPrice.eq(0) || sendTokenPrice.eq(0)) {
return {
amountToReceive: '0',
amountToReceiveConvertedToCurrency: 'USD 0',
}
}
const stakeAmount = new Decimal(stakeData.amount || 0)
const amountToReceive = stakeAmount.mul(sendTokenPrice).div(receiveTokenPrice)
const amountToReceiveConvertedToCurrency = amountToReceive.mul(receiveTokenPrice)
return {
amountToReceive: amountToReceive.toString(),
amountToReceiveConvertedToCurrency: `USD ${formatCurrency(amountToReceiveConvertedToCurrency)}`,
amountToReceiveConvertedToCurrency: `USD ${formatCurrency(amountToReceiveConvertedToCurrency.toNumber())}`,
}
}, [stakeData.amount, tokenToSend.price, tokenToReceive.price])

const stakePreviewFrom = useMemo(
() => ({
amount: toFixed(stakeData.amount),
amountConvertedToCurrency:
'USD ' + formatCurrency(Number(tokenToSend.price) * Number(stakeData.amount) ?? 0),
'USD ' + formatCurrency(Number(tokenToSend.price) * Number(stakeData.amount) || 0),
balance: tokenToSend.balance,
tokenSymbol: tokenToSend.symbol,
}),
Expand Down
9 changes: 0 additions & 9 deletions src/components/Table/Table.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,10 @@
import type { Meta, StoryObj } from '@storybook/react'
import { Table } from './Table'
import { tableSampleData } from './tableSampleData'
import tableDocs from './tableDocs.md'

const meta = {
title: 'Components/Table',
component: Table,
parameters: {
docs: {
description: {
// docs in MD format
component: tableDocs,
},
},
},
} satisfies Meta<typeof Table>

export default meta
Expand Down
5 changes: 4 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@
"paths": {
"@/*": ["./src/*"],
"@/public/*": ["./public/*"]
}
},
"types": [
"@testing-library/jest-dom"
]
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
Expand Down
15 changes: 15 additions & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'

export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: './vitest.setup.ts',
},
resolve: {
alias: {
'@': '/src',
},
},
})
4 changes: 4 additions & 0 deletions vitest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { expect } from 'vitest'
import * as matchers from '@testing-library/jest-dom/matchers'

expect.extend(matchers)