Skip to content

Commit

Permalink
Claiming rewards e2e tests. (#80)
Browse files Browse the repository at this point in the history
* Claiming rewards e2e tests

* fix deps issue.
  • Loading branch information
peiman3 authored Dec 7, 2024
1 parent b304bf8 commit 2c9d3ac
Show file tree
Hide file tree
Showing 9 changed files with 114 additions and 92 deletions.
54 changes: 54 additions & 0 deletions liquidity/cypress/cypress/e2e/42161-main/ARB_Claim_rewards.e2e.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { makeSearch } from '@snx-v3/useParams';

describe(__filename, () => {
Cypress.env('chainId', '42161');
Cypress.env('preset', 'main');
Cypress.env('walletAddress', '0xeEBb1b80e75b44180EbF7893DA00034d30BDfF7C');
Cypress.env('accountId', '170141183460469231731687303715884106023');

beforeEach(() => {
cy.task('startAnvil', {
chainId: Cypress.env('chainId'),
forkUrl: `https://arbitrum-mainnet.infura.io/v3/${Cypress.env('INFURA_KEY')}`,
block: '281318272',
}).then(() => cy.log('Anvil started'));

cy.on('window:before:load', (win) => {
win.localStorage.setItem('MAGIC_WALLET', Cypress.env('walletAddress'));
win.localStorage.setItem(
'DEFAULT_NETWORK',
`${Cypress.env('chainId')}-${Cypress.env('preset')}`
);
});
});
afterEach(() => cy.task('stopAnvil').then(() => cy.log('Anvil stopped')));

it(__filename, () => {
cy.setEthBalance({ balance: 100 });

cy.visit(
`?${makeSearch({
page: 'position',
collateralSymbol: 'ARB',
poolId: 1,
manageAction: 'deposit',
accountId: Cypress.env('accountId'),
})}`
);

cy.get('[data-cy="claim rewards submit"]').should('be.enabled');
cy.get('[data-cy="claim rewards submit"]').click();

cy.get('[data-cy="claim rewards dialog"]').should('exist');

cy.get('[data-cy="claim rewards info"]')
.should('exist')
.and('include.text', 'Claim your rewards');

cy.get('[data-cy="transaction hash"]').should('exist');

cy.contains('[data-status="success"]', 'Your rewards has been claimed.', {
timeout: 180_000,
}).should('exist');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { makeSearch } from '@snx-v3/useParams';

describe(__filename, () => {
Cypress.env('chainId', '8453');
Cypress.env('preset', 'andromeda');
Cypress.env('walletAddress', '0x1a245Fa866932731631E1ec8EDcDbB0C6A402559');
Cypress.env('accountId', '1640332659');

beforeEach(() => {
cy.task('startAnvil', {
chainId: Cypress.env('chainId'),
forkUrl: `https://base-mainnet.infura.io/v3/${Cypress.env('INFURA_KEY')}`,
block: '22544990',
}).then(() => cy.log('Anvil started'));

cy.on('window:before:load', (win) => {
win.localStorage.setItem('MAGIC_WALLET', Cypress.env('walletAddress'));
win.localStorage.setItem(
'DEFAULT_NETWORK',
`${Cypress.env('chainId')}-${Cypress.env('preset')}`
);
});
});
afterEach(() => cy.task('stopAnvil').then(() => cy.log('Anvil stopped')));

it(__filename, () => {
cy.setEthBalance({ balance: 100 });
cy.getUSDC({ amount: 500 });

cy.visit(
`?${makeSearch({
page: 'position',
collateralSymbol: 'USDC',
poolId: 1,
manageAction: 'deposit',
accountId: Cypress.env('accountId'),
})}`
);

cy.get('[data-cy="claim rewards submit"]').should('be.enabled');
cy.get('[data-cy="claim rewards submit"]').click();

cy.get('[data-cy="claim rewards dialog"]').should('exist');

cy.get('[data-cy="claim rewards info"]')
.should('exist')
.and('include.text', 'Claim your rewards');

cy.get('[data-cy="transaction hash"]').should('exist');

cy.contains('[data-status="success"]', 'Your rewards has been claimed.', {
timeout: 180_000,
}).should('exist');
});
});
1 change: 0 additions & 1 deletion liquidity/lib/useRewards/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
"main": "index.ts",
"version": "0.0.2",
"dependencies": {
"@snx-v3/constants": "workspace:*",
"@snx-v3/tsHelpers": "workspace:*",
"@snx-v3/useBlockchain": "workspace:*",
"@snx-v3/useCollateralTypes": "workspace:*",
Expand Down
78 changes: 0 additions & 78 deletions liquidity/lib/useRewards/useRewards.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { getSubgraphUrl } from '@snx-v3/constants';
import { useNetwork, useProvider } from '@snx-v3/useBlockchain';
import { useCollateralType } from '@snx-v3/useCollateralTypes';
import { useCoreProxy } from '@snx-v3/useCoreProxy';
Expand All @@ -21,33 +20,11 @@ const RewardsResponseSchema = z.array(
distributorAddress: z.string(),
decimals: z.number(),
claimableAmount: z.instanceof(Wei),
lifetimeClaimed: z.number(),
})
);

export type RewardsResponseType = z.infer<typeof RewardsResponseSchema>;

const RewardsDataDocument = `
query RewardsData($accountId: String!, $distributor: String!) {
rewardsClaimeds(where: { distributor: $distributor, account: $accountId }) {
id
amount
}
}
`;

const RewardsDistributionsDocument = `
query RewardsDistributions($distributor: String!) {
rewardsDistributions(where: { distributor: $distributor}) {
collateral_type
amount
duration
start
created_at
}
}
`;

export function useRewards({
poolId,
collateralSymbol,
Expand Down Expand Up @@ -125,32 +102,6 @@ export function useRewards({
if (filteredDistributors.length === 0) return [];

try {
const returnData = await Promise.all([
// Historical data for account id / distributor address pair
...filteredDistributors.map((distributor) =>
fetch(getSubgraphUrl(network?.name), {
method: 'POST',
body: JSON.stringify({
query: RewardsDataDocument,
variables: { accountId, distributor: distributor.address.toLowerCase() },
}),
}).then((res) => res.json())
),
// Metadata for each distributor
...filteredDistributors.map((distributor) =>
fetch(getSubgraphUrl(network?.name), {
method: 'POST',
body: JSON.stringify({
query: RewardsDistributionsDocument,
variables: { distributor: distributor.address.toLowerCase() },
}),
}).then((res) => res.json())
),
]);

const historicalData = returnData.slice(0, filteredDistributors.length);
const metaData = returnData.slice(filteredDistributors.length);

const CoreProxyContract = new ethers.Contract(CoreProxy.address, CoreProxy.abi, provider);

// Get claimable amount for each distributor
Expand Down Expand Up @@ -188,35 +139,12 @@ export function useRewards({
const results: RewardsResponseType = filteredDistributors.map((item: any, i: number) => {
// Amount claimable for this distributor
const claimableAmount = amounts[i];
const historicalClaims = historicalData[i]?.data?.rewardsClaimeds;
const distributions = metaData[i]?.data?.rewardsDistributions;
const symbol = item.payoutToken.symbol;
const synthToken = synthTokens?.find(
(synth) => synth?.address?.toUpperCase() === item?.payoutToken?.address?.toUpperCase()
);
const displaySymbol = synthToken ? synthToken?.symbol.slice(1) : symbol;

if (!distributions || !distributions.length) {
return {
address: item.address,
name: item.name,
symbol,
displaySymbol,
distributorAddress: item.address,
decimals: item.payoutToken.decimals,
payoutTokenAddress: item.payoutToken.address,
claimableAmount: wei(0),
lifetimeClaimed: historicalClaims
? historicalClaims
.reduce(
(acc: Wei, item: { amount: string }) => acc.add(wei(item.amount, 18, true)),
wei(0)
)
.toNumber()
: 0,
};
}

return {
address: item.address,
name: item.name,
Expand All @@ -226,12 +154,6 @@ export function useRewards({
decimals: item.payoutToken.decimals,
payoutTokenAddress: item.payoutToken.address,
claimableAmount,
lifetimeClaimed: historicalClaims
.reduce(
(acc: Wei, item: { amount: string }) => acc.add(wei(item.amount, 18, true)),
wei(0)
)
.toNumber(),
};
});

Expand Down
4 changes: 3 additions & 1 deletion liquidity/ui/src/components/Rewards/AllRewardsModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export const AllRewardsModal = ({ rewards, txnStatus, txnHash }: AllRewardsModal
borderColor="gray.900"
minWidth="384px"
>
<ModalBody p={6}>
<ModalBody data-cy="claim rewards dialog" p={6}>
<Text color="gray.50" fontSize="20px" fontWeight={700}>
Claiming Rewards
</Text>
Expand Down Expand Up @@ -93,6 +93,7 @@ export const AllRewardsModal = ({ rewards, txnStatus, txnHash }: AllRewardsModal
alignItems="space-between"
justifyContent="space-between"
ml={2}
data-cy="claim rewards info"
>
{rewards.map(({ collateralSymbol, amount }) => (
<Text
Expand Down Expand Up @@ -137,6 +138,7 @@ export const AllRewardsModal = ({ rewards, txnStatus, txnHash }: AllRewardsModal
mb={1}
borderTop="1px solid"
borderTopColor="gray.900"
data-cy="transaction hash"
>
<Link
variant="outline"
Expand Down
2 changes: 1 addition & 1 deletion liquidity/ui/src/components/Rewards/Rewards.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ export function Rewards() {
opacity: 0.5,
cursor: 'not-allowed',
}}
data-cy="claim rewards submit"
onClick={() => claimAll()}
>
Claim
Expand Down Expand Up @@ -147,7 +148,6 @@ export function Rewards() {
key={item.address}
displaySymbol={item.displaySymbol}
claimableAmount={item.claimableAmount}
lifetimeClaimed={item.lifetimeClaimed}
distributorAddress={item.distributorAddress}
/>
))
Expand Down
1 change: 0 additions & 1 deletion liquidity/ui/src/components/Rewards/RewardsRow.cy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ describe('RewardsRow', () => {
<RewardsRow
displaySymbol="ETH"
claimableAmount={wei(50)}
lifetimeClaimed={25}
distributorAddress="0x123456789abcdef"
/>
</Table>
Expand Down
10 changes: 1 addition & 9 deletions liquidity/ui/src/components/Rewards/RewardsRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,18 @@ import { etherscanLink } from '@snx-v3/etherscanLink';
import { truncateAddress } from '@snx-v3/formatters';
import { Tooltip } from '@snx-v3/Tooltip';
import { useNetwork } from '@snx-v3/useBlockchain';
import Wei, { wei } from '@synthetixio/wei';
import Wei from '@synthetixio/wei';
import { TokenIcon } from '../TokenIcon/TokenIcon';

interface RewardsRowInterface {
displaySymbol?: string;
claimableAmount: Wei; // The immediate amount claimable as read from the contracts
lifetimeClaimed: number;
distributorAddress: string;
}

export const RewardsRow = ({
displaySymbol,
claimableAmount,
lifetimeClaimed,
distributorAddress,
}: RewardsRowInterface) => {
const { network } = useNetwork();
Expand Down Expand Up @@ -64,12 +62,6 @@ export const RewardsRow = ({
>
<Amount value={claimableAmount} showTooltip />
</Text>
{lifetimeClaimed > 0 && (
<Text color="gray.500" fontSize="12px" fontFamily="heading" lineHeight="16px">
<Tooltip label="Total claimed over lifetime">Lifetime: &nbsp;</Tooltip>
<Amount value={wei(lifetimeClaimed)} />
</Text>
)}
</Fade>
</Td>
</Tr>
Expand Down
1 change: 0 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5996,7 +5996,6 @@ __metadata:
version: 0.0.0-use.local
resolution: "@snx-v3/useRewards@workspace:liquidity/lib/useRewards"
dependencies:
"@snx-v3/constants": "workspace:*"
"@snx-v3/tsHelpers": "workspace:*"
"@snx-v3/useBlockchain": "workspace:*"
"@snx-v3/useCollateralTypes": "workspace:*"
Expand Down

0 comments on commit 2c9d3ac

Please sign in to comment.