Skip to content

Commit

Permalink
Fix for optional synth token (#103)
Browse files Browse the repository at this point in the history
* Typescript for contract importers

* Remove unused component

* Sort contract imports

* Separate useCreateAccount from useAccounts

* Better Borrow test, checking stats

* Fix for synths may not have `token`, invalidate query cache after mutations

* Yarn install =/

* e2e tests update: wait for results of rewards claiming and synths unwrapping

* Wrap custom cypress commands and fine-tune timeouts

* Invalidate relevant queries after mutations and keep account id as BigNumber

* fix stataUSDC_Claim_rewards.e2e.js

* Remove all unnecessary hooks from ClosePosition and reuse existing useLiquidityPosition

* Add loading state for deposit

* Iterator.prototype.toArray() has limited availability
  • Loading branch information
noisekit authored Dec 15, 2024
1 parent 5b0de3c commit 98feaa6
Show file tree
Hide file tree
Showing 139 changed files with 1,901 additions and 2,582 deletions.
24 changes: 13 additions & 11 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,19 @@ commands:
- &yarn_state_cache yarn-install-state-{{ .Environment.NODE_MODULES_VERSION }}-{{ checksum "/tmp/month.txt" }}-{{ checksum "yarn.lock" }}
- yarn-install-state-{{ .Environment.NODE_MODULES_VERSION }}-{{ checksum "/tmp/month.txt" }}-

- run:
name: Fallback to installing node modules in case of cache corruption
command: |-
# Check if we restored cache and have node_modules already
if [ -f "node_modules/.yarn-state.yml" ] && [ -f ".yarn/install-state.gz" ]; then
echo "node_modules restored from cache"
exit 0
else
echo "node_modules could not be restored from cache, activating fallback installation"
yarn install --immutable
fi
- run: yarn install --immutable

# - run:
# name: Fallback to installing node modules in case of cache corruption
# command: |-
# # Check if we restored cache and have node_modules already
# if [ -f "node_modules/.yarn-state.yml" ] && [ -f ".yarn/instalUSDC_l-state.gz" ]; then
# echo "node_modules restored from cache"
# exit 0
# else
# echo "node_modules could not be restored from cache, activating fallback installation"
# yarn install --immutable
# fi

- save_cache:
key: *yarn_cache
Expand Down
26 changes: 1 addition & 25 deletions liquidity/components/ClaimModal/ClaimModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,12 @@ import { useLiquidityPosition } from '@snx-v3/useLiquidityPosition';
import { type PositionPageSchemaType, useParams } from '@snx-v3/useParams';
import { useSystemToken } from '@snx-v3/useSystemToken';
import { wei } from '@synthetixio/wei';
import { useQueryClient } from '@tanstack/react-query';
import { useCallback, useContext, useMemo } from 'react';
import { LiquidityPositionUpdated } from '../../ui/src/components/Manage/LiquidityPositionUpdated';

export function ClaimModal({ onClose }: { onClose: () => void }) {
const [params] = useParams<PositionPageSchemaType>();
const { debtChange, setDebtChange } = useContext(ManagePositionContext);
const queryClient = useQueryClient();
const { network } = useNetwork();
const { data: collateralType } = useCollateralType(params.collateralSymbol);
const { data: liquidityPosition } = useLiquidityPosition({
Expand Down Expand Up @@ -58,25 +56,12 @@ export function ClaimModal({ onClose }: { onClose: () => void }) {
const execBorrowWithErrorParser = useCallback(async () => {
try {
await execBorrow();

queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPosition'],
exact: false,
});
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'TokenBalance'],
});
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'AccountCollateralUnlockDate'],
});

setDebtChange(ZEROWEI);
} catch (error: any) {
const contractError = errorParser(error);
if (contractError) {
console.error(new Error(contractError.name), contractError);
}

toast.closeAll();
toast({
title: isBorrow ? 'Borrow' : 'Claim' + ' failed',
Expand All @@ -91,16 +76,7 @@ export function ClaimModal({ onClose }: { onClose: () => void }) {
});
throw Error(isBorrow ? 'Borrow' : 'Claim' + ' failed', { cause: error });
}
}, [
execBorrow,
queryClient,
network?.id,
network?.preset,
setDebtChange,
errorParser,
toast,
isBorrow,
]);
}, [execBorrow, setDebtChange, errorParser, toast, isBorrow]);

const symbol =
network?.preset === 'andromeda' ? collateralType?.displaySymbol : systemToken?.symbol;
Expand Down
1 change: 0 additions & 1 deletion liquidity/components/ClaimModal/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
"@snx-v3/useParams": "workspace:*",
"@snx-v3/useSystemToken": "workspace:*",
"@synthetixio/wei": "^2.74.4",
"@tanstack/react-query": "^5.8.3",
"react": "^18.2.0"
}
}
45 changes: 9 additions & 36 deletions liquidity/components/DepositModal/DepositModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,9 @@ import { useLiquidityPosition } from '@snx-v3/useLiquidityPosition';
import { type PositionPageSchemaType, useParams } from '@snx-v3/useParams';
import { usePool } from '@snx-v3/usePools';
import { useSpotMarketProxy } from '@snx-v3/useSpotMarketProxy';
import { useSynthTokens } from '@snx-v3/useSynthTokens';
import { useSynthToken } from '@snx-v3/useSynthToken';
import { useWrapEth } from '@snx-v3/useWrapEth';
import { Wei, wei } from '@synthetixio/wei';
import { useQueryClient } from '@tanstack/react-query';
import { useMachine } from '@xstate/react';
import { ethers } from 'ethers';
import React from 'react';
Expand All @@ -38,7 +37,6 @@ export function DepositModal({
title?: string;
}) {
const [params, setParams] = useParams<PositionPageSchemaType>();
const queryClient = useQueryClient();
const { network } = useNetwork();
const { collateralChange, setCollateralChange } = React.useContext(ManagePositionContext);
const { data: CoreProxy } = useCoreProxy();
Expand All @@ -50,12 +48,7 @@ export function DepositModal({
collateralType,
});

const { data: synthTokens } = useSynthTokens();
const synth = synthTokens?.find(
(synth) =>
collateralType?.tokenAddress?.toLowerCase() === synth?.address?.toLowerCase() ||
collateralType?.tokenAddress?.toLowerCase() === synth?.token?.address.toLowerCase()
);
const { data: synthToken } = useSynthToken(collateralType);

const currentCollateral = liquidityPosition?.collateralAmount ?? ZEROWEI;
const availableCollateral = liquidityPosition?.availableCollateral ?? ZEROWEI;
Expand Down Expand Up @@ -87,16 +80,16 @@ export function DepositModal({
//Collateral Approval
const { approve, requireApproval } = useApprove({
contractAddress:
network?.preset === 'andromeda' ? synth?.token?.address : collateralType?.tokenAddress,
network?.preset === 'andromeda' ? synthToken?.token?.address : collateralType?.tokenAddress,

amount: collateralChange.lte(availableCollateral)
? wei(0).toBN()
: network?.preset === 'andromeda' && synth
: network?.preset === 'andromeda' && synthToken && synthToken.token
? collateralChange
.sub(availableCollateral)
.toBN()
// Reduce precision for approval of USDC on Andromeda
.mul(ethers.utils.parseUnits('1', synth.token.decimals))
.mul(ethers.utils.parseUnits('1', synthToken.token.decimals))
.div(D18)
: collateralChange.sub(availableCollateral).toBN(),
spender: network?.preset === 'andromeda' ? SpotMarketProxy?.address : CoreProxy?.address,
Expand All @@ -118,7 +111,7 @@ export function DepositModal({
accountId: params.accountId,
newAccountId,
poolId: params.poolId,
collateralTypeAddress: synth?.token.address,
collateralTypeAddress: synthToken?.token?.address,
collateralChange,
currentCollateral,
availableCollateral,
Expand Down Expand Up @@ -169,7 +162,9 @@ export function DepositModal({
toast({
title: `Approve collateral for transfer`,
description: `Approve ${
network?.preset === 'andromeda' ? synth?.token?.address : collateralType?.tokenAddress
network?.preset === 'andromeda'
? synthToken?.token?.address
: collateralType?.tokenAddress
} transfer`,
status: 'info',
variant: 'left-accent',
Expand Down Expand Up @@ -220,27 +215,6 @@ export function DepositModal({
await execDeposit();
}

queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'TokenBalance'],
});
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'EthBalance'],
});
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPosition'],
});
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'TransferableSynthetix'],
});
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'Allowance'],
});
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPositions'],
});
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'Accounts'],
});
setCollateralChange(ZEROWEI);

toast.closeAll();
Expand All @@ -256,7 +230,6 @@ export function DepositModal({
if (contractError) {
console.error(new Error(contractError.name), contractError);
}

toast.closeAll();
toast({
title: 'Could not complete locking collateral',
Expand Down
60 changes: 18 additions & 42 deletions liquidity/components/DepositModal/StataDepositModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { currency } from '@snx-v3/format';
import { ManagePositionContext } from '@snx-v3/ManagePositionContext';
import { Multistep } from '@snx-v3/Multistep';
import { useApprove } from '@snx-v3/useApprove';
import { useNetwork } from '@snx-v3/useBlockchain';
import { useCollateralType } from '@snx-v3/useCollateralTypes';
import { useContractErrorParser } from '@snx-v3/useContractErrorParser';
import { useConvertStataUSDC } from '@snx-v3/useConvertStataUSDC';
Expand All @@ -18,11 +17,10 @@ import { usePool } from '@snx-v3/usePools';
import { useSpotMarketProxy } from '@snx-v3/useSpotMarketProxy';
import { useStaticAaveUSDC } from '@snx-v3/useStaticAaveUSDC';
import { useStaticAaveUSDCRate } from '@snx-v3/useStaticAaveUSDCRate';
import { useSynthTokens } from '@snx-v3/useSynthTokens';
import { useSynthToken } from '@snx-v3/useSynthToken';
import { useTokenBalance } from '@snx-v3/useTokenBalance';
import { useUSDC } from '@snx-v3/useUSDC';
import { Wei, wei } from '@synthetixio/wei';
import { useQueryClient } from '@tanstack/react-query';
import { useMachine } from '@xstate/react';
import { ethers } from 'ethers';
import React from 'react';
Expand All @@ -41,8 +39,6 @@ export function StataDepositModal({
title?: string;
}) {
const [params, setParams] = useParams<PositionPageSchemaType>();
const queryClient = useQueryClient();
const { network } = useNetwork();
const { collateralChange, setCollateralChange } = React.useContext(ManagePositionContext);
const { data: SpotMarketProxy } = useSpotMarketProxy();

Expand All @@ -57,12 +53,7 @@ export function StataDepositModal({
const { data: staticAaveUSDCRate } = useStaticAaveUSDCRate();
// log('staticAaveUSDCRate', staticAaveUSDCRate, `${staticAaveUSDCRate}`);

const { data: synthTokens } = useSynthTokens();
const synth = synthTokens?.find(
(synth) =>
collateralType?.tokenAddress?.toLowerCase() === synth?.address?.toLowerCase() ||
collateralType?.tokenAddress?.toLowerCase() === synth?.token?.address.toLowerCase()
);
const { data: synthToken } = useSynthToken(collateralType);

const { data: stataUSDCTokenBalanceRaw } = useTokenBalance(StaticAaveUSDC?.address);
// log(
Expand Down Expand Up @@ -130,17 +121,18 @@ export function StataDepositModal({
? collateralChange.sub(liquidityPosition.availableCollateral)
: wei(0);
const { approve: approveStata, requireApproval: requireApprovalStata } = useApprove({
contractAddress: synth?.token?.address,
amount: synth
? stataApprovalNeeded
.toBN()
.mul(ethers.utils.parseUnits('1', synth.token.decimals))
.div(D18)

// extra 1% approval
.mul(101)
.div(100)
: undefined,
contractAddress: synthToken?.token?.address,
amount:
synthToken && synthToken.token
? stataApprovalNeeded
.toBN()
.mul(ethers.utils.parseUnits('1', synthToken.token.decimals))
.div(D18)

// extra 1% approval
.mul(101)
.div(100)
: undefined,
spender: SpotMarketProxy?.address,
});
// log('requireApprovalStata', requireApprovalStata);
Expand All @@ -152,7 +144,7 @@ export function StataDepositModal({
accountId: params.accountId,
newAccountId,
poolId: params.poolId,
collateralTypeAddress: synth?.token.address,
collateralTypeAddress: synthToken?.token?.address,
collateralChange,
currentCollateral: liquidityPosition?.collateralAmount,
availableCollateral: liquidityPosition?.availableCollateral,
Expand Down Expand Up @@ -196,6 +188,7 @@ export function StataDepositModal({
),
status: 'error',
variant: 'left-accent',
duration: 3_600_000,
});
throw Error('Approve failed', { cause: error });
}
Expand Down Expand Up @@ -224,6 +217,7 @@ export function StataDepositModal({
),
status: 'error',
variant: 'left-accent',
duration: 3_600_000,
});
throw Error('Wrap USDC failed', { cause: error });
}
Expand All @@ -236,7 +230,7 @@ export function StataDepositModal({
}
toast({
title: `Approve collateral for transfer`,
description: `Approve ${synth?.token?.address} transfer`,
description: `Approve ${synthToken?.token?.address} transfer`,
status: 'info',
variant: 'left-accent',
});
Expand Down Expand Up @@ -286,24 +280,6 @@ export function StataDepositModal({

await depositBaseAndromeda();

queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'TokenBalance'],
});
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPosition'],
});
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'TransferableSynthetix'],
});
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'Allowance'],
});
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPositions'],
});
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'Accounts'],
});
setCollateralChange(ZEROWEI);

toast.closeAll();
Expand Down
3 changes: 1 addition & 2 deletions liquidity/components/DepositModal/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,11 @@
"@snx-v3/useSpotMarketProxy": "workspace:*",
"@snx-v3/useStaticAaveUSDC": "workspace:*",
"@snx-v3/useStaticAaveUSDCRate": "workspace:*",
"@snx-v3/useSynthTokens": "workspace:*",
"@snx-v3/useSynthToken": "workspace:*",
"@snx-v3/useTokenBalance": "workspace:*",
"@snx-v3/useUSDC": "workspace:*",
"@snx-v3/useWrapEth": "workspace:*",
"@synthetixio/wei": "^2.74.4",
"@tanstack/react-query": "^5.8.3",
"@xstate/react": "^3.2.2",
"ethers": "^5.7.2",
"react": "^18.2.0",
Expand Down
14 changes: 0 additions & 14 deletions liquidity/components/RepayModal/RepayModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import { useSpotMarketProxy } from '@snx-v3/useSpotMarketProxy';
import { useSynthTokens } from '@snx-v3/useSynthTokens';
import { useSystemToken } from '@snx-v3/useSystemToken';
import { useTokenBalance } from '@snx-v3/useTokenBalance';
import { useQueryClient } from '@tanstack/react-query';
import { useMachine } from '@xstate/react';
import React from 'react';
import { LiquidityPositionUpdated } from '../../ui/src/components/Manage/LiquidityPositionUpdated';
Expand All @@ -30,7 +29,6 @@ export function RepayModal({ onClose }: { onClose: () => void }) {
const [params] = useParams<PositionPageSchemaType>();

const { network } = useNetwork();
const queryClient = useQueryClient();

const { data: collateralType } = useCollateralType(params.collateralSymbol);

Expand Down Expand Up @@ -135,18 +133,6 @@ export function RepayModal({ onClose }: { onClose: () => void }) {
await execRepay();
}

await Promise.all([
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'TokenBalance'],
}),
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'Allowance'],
}),
queryClient.invalidateQueries({
queryKey: [`${network?.id}-${network?.preset}`, 'LiquidityPosition'],
}),
]);

setDebtChange(ZEROWEI);

toast.closeAll();
Expand Down
1 change: 0 additions & 1 deletion liquidity/components/RepayModal/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
"@snx-v3/useSynthTokens": "workspace:*",
"@snx-v3/useSystemToken": "workspace:*",
"@snx-v3/useTokenBalance": "workspace:*",
"@tanstack/react-query": "^5.8.3",
"@xstate/react": "^3.2.2",
"react": "^18.2.0",
"xstate": "^4.38.3"
Expand Down
Loading

0 comments on commit 98feaa6

Please sign in to comment.