8000 fix: Stake Pool table improvements by colbr · Pull Request #413 · zer0-os/zNS-dapp · GitHub
[go: up one dir, main page]

Skip to content
8000
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
94,184 changes: 32,703 additions & 61,481 deletions package-lock.json

Large diffs are not rendered by default.

19 changes: 9 additions & 10 deletions src/components/Inputs/TextInput/TextInputWithTopPlaceHolder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@ interface TextInputWithTopPlaceHolderProps extends TextInputProps {
topPlaceholder: string;
}

const TextInputWithTopPlaceHolder: React.FC<
TextInputWithTopPlaceHolderProps
> = ({ topPlaceholder, ...props }) => {
return (
<div className={styles.TextInputTopPlaceholderWrapper}>
<span className={styles.TopPlaceholder}>{topPlaceholder}</span>
<TextInput {...props} className={styles.TextInputTopPlaceholder} />
</div>
);
};
const TextInputWithTopPlaceHolder: React.FC<TextInputWithTopPlaceHolderProps> =
({ topPlaceholder, ...props }) => {
return (
<div className={styles.TextInputTopPlaceholderWrapper}>
<span className={styles.TopPlaceholder}>{topPlaceholder}</span>
<TextInput {...props} className={styles.TextInputTopPlaceholder} />
</div>
);
};

export default TextInputWithTopPlaceHolder;
4 changes: 1 addition & 3 deletions src/components/Tables/GenericTable/GenericTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import styles from './GenericTable.module.scss';
import { useInView } from 'react-intersection-observer';
import { useCurrentDomain } from 'lib/providers/CurrentDomainProvider';
import { usePropsState } from 'lib/hooks/usePropsState';
import { IconButton, SearchBar, Spinner, TextButton } from 'components';
import grid from './assets/grid.svg';
Expand All @@ -18,9 +17,8 @@ const GenericTable = (props: any) => {
///////////////////////
// State & Variables //
///////////////////////
const { domainMetadata } = useCurrentDomain();
const isGridViewByDefault =
window.innerWidth <= 700 || Boolean(domainMetadata?.gridViewByDefault);
8000 window.innerWidth <= 700 || props.isGridViewByDefault;

// chunk defines which row we're up to when infinite scroll is enabled
// i.e., chunk 2 with chunkSize 6 means we've loaded 12 rows
Expand Down
1 change: 1 addition & 0 deletions src/containers/Tables/SubdomainTable/SubdomainTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ const SubdomainTable = ({ style }: SubdomainTableProps) => {
infiniteScroll
isLoading={isLoading || isDomainLoading}
loadingText={'Loading Subdomains'}
isGridViewByDefault={domainMetadata?.gridViewByDefault}
style={style}
/>
</>
Expand Down
3 changes: 3 additions & 0 deletions src/containers/staking/Deposits/Deposits.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
> * {
flex: 1;

height: unset;
align-content: stretch;

&:not(:last-child) {
margin-right: 16px;
}
Expand Down
4 changes: 2 additions & 2 deletions src/containers/staking/Deposits/Deposits.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,11 @@ const Deposits = () => {
<StatsWidget
className="normalView"
fieldName={'Your Total Stake (USD)'}
isLoading={account !== null && !totalStakedUsd}
isLoading={totalStakedUsd === undefined}
title={
account && totalStakedUsd !== undefined
? '$' + toFiat(totalStakedUsd) + ' USD'
: '-'
: '$0'
}
/>
</ul>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,7 @@ export const TABLE_HEADERS_DISCONNECTED = [
className: '',
},
];

export enum MESSAGE {
FAILED_TO_LOAD = 'Failed to load',
}
2 changes: 1 addition & 1 deletion src/containers/staking/StakePoolTable/StakePoolTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import styles from './StakePoolTable.module.scss';
import {
TABLE_HEADERS,
TABLE_HEADERS_DISCONNECTED,
} from './StakePoolTable.helpers';
} from './StakePoolTable.constants';
import { useWeb3React } from '@web3-react/core';

const StakePoolTable = () => {
Expand Down
177 changes: 177 additions & 0 deletions src/containers/staking/StakePoolTable/StakePoolTableRow.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import '@testing-library/jest-dom/extend-expect';
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Perfect test!

import {
fireEvent,
render,
screen,
waitForElementToBeRemoved,
} from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

import { ethers } from 'ethers';

import {
MESSAGE,
TABLE_HEADERS,
TABLE_HEADERS_DISCONNECTED,
} from './StakePoolTable.constants';
import StakePoolTableRow, { TEST_ID } from './StakePoolTableRow';

//////////
// Mock //
//////////

var mockUserValueStaked = jest.fn();

/**
* Note:
* This is directly copied from pool output in SDK
* as of Fri 18 Mar 2022
*/
Comment on lines +25 to +29
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nice comment 💯

const mockPoolData = {
instance: {
address: '0x9E87a268D42B0Aba399C121428fcE2c626Ea01FF',
userValueStaked: mockUserValueStaked,
},
content: {
image: '/staking/farm.png',
name: 'Farm WILD - WETH LP',
token: 'Liquidity Provider',
tokenTicker: 'LP',
domain: '/pools/lp',
tokenPurchaseUrl: '',
},
metrics: {
apy: 145.03269039595662,
tvl: {
numberOfTokens: 35576.6553275205,
valueOfTokensUSD: 6971564.4606713345,
},
},
};

const mockUserData = {
userValueUnlocked: ethers.utils.parseEther('1000'),
userValueLocked: ethers.utils.parseEther('1000'),
};

var mockAccountValid = { account: '1' };
var mockAccountInvalid = { account: undefined };
var mockAccount: { account: string | undefined } = mockAccountValid;

jest.mock('@web3-react/core', () => ({
useWeb3React: () => mockAccount,
}));

var mockSelectStakePool = jest.fn();
jest.mock('lib/providers/staking/PoolSelectProvider', () => ({
useStakingPoolSelector: () => ({
selectStakePool: mockSelectStakePool,
}),
}));

///////////
// Setup //
///////////

const renderComponent = () => {
return render(
<table>
<tbody>
<StakePoolTableRow data={mockPoolData} rowNumber={'1'} />
</tbody>
</table>,
Comment on lines +78 to +82
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I don't think we need <table>, <tbody> because it is the testing of StakePoolTableRow componnent. But its okay.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Was getting some compile errors for not putting a <tr> in a <table> and <tbody>, very painful

);
};

const jestConsole = console;
const consoleError = console.error;

beforeEach(() => {
global.console = require('console');
console.error = jest.fn();
});

afterEach(() => {
mockAccount = mockAccountValid; // reset mock account value
global.console = jestConsole;
console.error = consoleError;
});

///////////
// Tests //
///////////

test('should render', async () => {
mockUserValueStaked.mockResolvedValue(mockUserData);
renderComponent();
await screen.findByText(mockPoolData.content.name);
});

test('should render correct number of columns with wallet connected', async () => {
mockUserValueStaked.mockResolvedValue(mockUserData);
const { getByTestId } = renderComponent();
await screen.findByText(mockPoolData.content.name);
expect(getByTestId(TEST_ID.CONTAINER).childElementCount).toBe(
TABLE_HEADERS.length,
);
});

test('should render correct number of columns with wallet disconnected', async () => {
mockAccount = mockAccountInvalid;
const { getByTestId } = renderComponent();
await screen.findByText(mockPoolData.content.name);
expect(getByTestId(TEST_ID.CONTAINER).childElementCount).toBe(
TABLE_HEADERS_DISCONNECTED.length,
);
});

test('should handle row click event', async () => {
mockUserValueStaked.mockResolvedValue(mockUserData);
const { getByTestId } = renderComponent();
await screen.findByText(mockPoolData.content.name);
const container = getByTestId(TEST_ID.CONTAINER);
fireEvent.click(container);
expect(mockSelectStakePool).toBeCalledWith(mockPoolData);
});

test('should handle button click event', async () => {
mockUserValueStaked.mockResolvedValue(mockUserData);
renderComponent();
await screen.findByText(mockPoolData.content.name);
const button = screen.getByRole('button', { name: 'Stake' });
fireEvent.mouseUp(button);
expect(mockSelectStakePool).toBeCalledWith(mockPoolData);
});

test('should render spinner while loading', async 10BC8 () => {
mockUserValueStaked.mockResolvedValue(mockUserData);
const { getByTestId } = renderComponent();
const spinner = getByTestId(TEST_ID.SPINNER);
expect(spinner).toBeInTheDocument();
await waitForElementToBeRemoved(spinner);
});

test('should handle failed load', async () => {
mockUserValueStaked.mockRejectedValue(undefined);
renderComponent();
await screen.findByText(MESSAGE.FAILED_TO_LOAD);
expect(console.error).toBeCalledTimes(1);
});

test('should format apy correctly', async () => {
mockUserValueStaked.mockResolvedValue(mockUserData);
renderComponent();
await screen.findByText('145.03%');
});

test('should format total stake correctly', async () => {
mockUserValueStaked.mockResolvedValue(mockUserData);
renderComponent();
await screen.findByText('$6,971,564.46');
});

test('should format user stake correctly', async () => {
mockUserValueStaked.mockResolvedValue(mockUserData);
renderComponent();
await screen.findByText('2,000.00 ' + mockPoolData.content.tokenTicker);
});
77 changes: 54 additions & 23 deletions src/containers/staking/StakePoolTable/StakePoolTableRow.tsx
Original file line number Diff line number Diff line change
@@ -1,47 +1,78 @@
/**
* This component represents a single row rendered by StakePoolTable
*/
import { useState } from 'react';
import { FutureButton, Spinner } from 'components';
import { Artwork } from 'components';
import styles from './StakePoolTableRow.module.scss';

// Hook imports
import { useWeb3React } from '@web3-react/core';
import { useUpdateEffect } from 'lib/hooks/useUpdateEffect';
import { useDidMount } from 'lib/hooks/useDidMount';
import { useStakingPoolSelector } from 'lib/providers/staking/PoolSelectProvider';

// Library imports
import { WrappedStakingPool } from 'lib/providers/staking/StakingProviderTypes';
import { displayEther, toFiat } from 'lib/currency';
import { ethers } from 'ethers';
import { useWeb3React } from '@web3-react/core';
import { useUpdateEffect } from 'lib/hooks/useUpdateEffect';

import { Artwork, FutureButton, Spinner } from 'components';

// Local imports
import { MESSAGE } from './StakePoolTable.constants';
import styles from './StakePoolTableRow.module.scss';

export const TEST_ID = {
CONTAINER: 'stake-pool-table-container',
SPINNER: 'stake-pool-row-spinner',
};

const StakePoolTableRow = (props: any) => {
const selectPool = useStakingPoolSelector().selectStakePool;
const { account } = useWeb3React();

const [isLoading, setIsLoading] = useState<boolean>(true);
const [totalStake, setTotalStake] = useState<ethers.BigNumber | undefined>();
const pool = props.data as WrappedStakingPool;
const apy = pool.metrics.apy;
const tvl = pool.metrics.tvl.valueOfTokensUSD;

const getStake = async (id: string) => {
try {
const { userValueLocked, userValueUnlocked } =
await pool.instance.userValueStaked(id);
setTotalStake(userValueUnlocked.add(userValueLocked));
} catch (e: any) {
/**
* Gets user's stake and assigns it to state variables
* @returns void
*/
const getStake = () => {
if (!account) {
setTotalStake(ethers.BigNumber.from(0));
console.error(e);
return;
}
setTotalStake(undefined);
setIsLoading(true);
pool.instance
.userValueStaked(account)
.then((value) => {
const { userValueLocked, userValueUnlocked } = value;
setTotalStake(userValueUnlocked.add(userValueLocked));
setIsLoading(false);
})
.catch((e: any) => {
setIsLoading(false);
console.error(e);
});
};

useUpdateEffect(() => {
if (account) {
getStake(account);
}
}, [pool]);
useUpdateEffect(getStake, [pool, account]);

useDidMount(getStake);

const => {
selectPool(pool);
};

return (
<tr className={styles.Row} >
<tr
className={styles.Row}
>
data-testid={TEST_ID.CONTAINER}
>
<td>{props.rowNumber + 1}</td>
<td>
<Artwork
Expand All @@ -58,12 +89,12 @@ const StakePoolTableRow = (props: any) => {
</td>
{account ? (
<td className={styles.Right}>
{totalStake === undefined ? (
<Spinner />
{isLoading ? (
<Spinner data-testid={TEST_ID.SPINNER} />
) : totalStake ? (
`${displayEther(totalStake)} ${pool.content.tokenTicker}`
) : (
<>
{displayEther(totalStake)} {pool.content.tokenTicker}
</>
MESSAGE.FAILED_TO_LOAD
)}
</td>
) : (
Expand Down
0