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

Exclude locked collateral from available to withdraw. #121

Open
wants to merge 5 commits into
base: master
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
1 change: 1 addition & 0 deletions liquidity/lib/useAccountCollateral/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './useAccountCollateral';
17 changes: 17 additions & 0 deletions liquidity/lib/useAccountCollateral/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "@snx-v3/useAccountCollateral",
"private": true,
"main": "index.ts",
"version": "0.0.1",
"dependencies": {
"@snx-v3/tsHelpers": "workspace:*",
"@snx-v3/useBlockchain": "workspace:*",
"@snx-v3/useCoreProxy": "workspace:*",
"@snx-v3/withERC7412": "workspace:*",
"@synthetixio/wei": "^2.74.4",
"@tanstack/react-query": "^5.8.3",
"debug": "^4.3.7",
"ethers": "^5.7.2",
"react": "^18.2.0"
}
}
74 changes: 74 additions & 0 deletions liquidity/lib/useAccountCollateral/useAccountCollateral.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { contractsHash } from '@snx-v3/tsHelpers';
import { Network, useNetwork, useProviderForChain } from '@snx-v3/useBlockchain';
import { useCoreProxy } from '@snx-v3/useCoreProxy';
import { erc7412Call } from '@snx-v3/withERC7412';
import Wei, { wei } from '@synthetixio/wei';
import { useQuery } from '@tanstack/react-query';
import debug from 'debug';
import { ethers } from 'ethers';

const log = debug('snx:useAccountCollateral');

export const useAccountCollateral = ({
accountId,
tokenAddress,
network: networkOverride,
}: {
accountId?: string;
tokenAddress?: string;
network?: Network;
}) => {
const { network: currentNetwork } = useNetwork();
const network = networkOverride || currentNetwork;
const { data: CoreProxy } = useCoreProxy(network);
const provider = useProviderForChain(network);

return useQuery({
queryKey: [
`${network?.id}-${network?.preset}`,
'AccountCollateral',
{ accountId },
{ tokenAddress },
{ contractsHash: contractsHash([CoreProxy]) },
],
enabled: Boolean(
network && provider && CoreProxy && accountId && tokenAddress && network.id === 1
),
queryFn: async (): Promise<{
totalDeposited: Wei;
totalAssigned: Wei;
totalLocked: Wei;
}> => {
if (!(network && provider && CoreProxy && accountId && tokenAddress)) {
throw new Error('OMFG');
}
const CoreProxyContract = new ethers.Contract(CoreProxy.address, CoreProxy.abi, provider);

const getAccountCollateralCallPromised =
CoreProxyContract.populateTransaction.getAccountCollateral(accountId, tokenAddress);
const calls = await Promise.all([getAccountCollateralCallPromised]);

return await erc7412Call(
network,
provider,
calls,
(encoded) => {
if (!Array.isArray(encoded) || calls.length !== encoded.length) {
throw new Error('[useAccountCollateral] Unexpected multicall response');
}

const [totalDeposited, totalAssigned, totalLocked] =
CoreProxyContract.interface.decodeFunctionResult('getAccountCollateral', encoded[0]);

log({ totalDeposited, totalAssigned, totalLocked });
return {
totalDeposited: wei(totalDeposited),
totalAssigned: wei(totalAssigned),
totalLocked: wei(totalLocked),
};
},
'useAccountCollateral'
);
},
});
};
32 changes: 32 additions & 0 deletions liquidity/ui/src/components/Manage/CollateralStats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { useCollateralType } from '@snx-v3/useCollateralTypes';
import { useLiquidityPosition } from '@snx-v3/useLiquidityPosition';
import { type PositionPageSchemaType, useParams } from '@snx-v3/useParams';
import { type Wei } from '@synthetixio/wei';
import { useAccountCollateral } from '../../../../lib/useAccountCollateral';
import { Amount } from '@snx-v3/Amount';

export function CollateralStats({
newCollateralAmount,
Expand All @@ -21,6 +23,10 @@ export function CollateralStats({
accountId: params.accountId,
collateralType,
});
const { data: accountCollateral } = useAccountCollateral({
accountId: params.accountId,
tokenAddress: collateralType?.address,
});

return (
<BorderBox maxW={['100%', '50%']} p={4} flex="1" flexDirection="row" bg="navy.700">
Expand Down Expand Up @@ -67,7 +73,33 @@ export function CollateralStats({
) : null}
</Flex>
</Flex>

{accountCollateral?.totalLocked.gt(0) && (
<Flex mt={4} alignItems="center" gap={3}>
<Text color="gray.500" fontSize="sm" fontFamily="heading" lineHeight="16px">
Escrowed
</Text>
<Text
color="white"
fontSize="sm"
fontFamily="heading"
lineHeight="16px"
fontWeight={700}
>
<Amount
value={accountCollateral.totalLocked}
suffix={` ${collateralType?.displaySymbol}`}
showTooltip
/>
</Text>
</Flex>
)}
</Flex>
</BorderBox>
);
}

//totalAssigned
302.8257661995;
//
302.8257661995;
50 changes: 48 additions & 2 deletions liquidity/ui/src/components/Positions/PositionsRow.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { TimeIcon } from '@chakra-ui/icons';
import { Box, Button, Collapse, Fade, Flex, Link, Td, Text, Tooltip } from '@chakra-ui/react';
import {
Box,
Button,
Collapse,
Fade,
Flex,
Image,
Link,
Td,
Text,
Tooltip,
} from '@chakra-ui/react';
import { Amount } from '@snx-v3/Amount';
import { DebtAmount, PnlAmount } from '@snx-v3/DebtAmount';
import { TokenIcon } from '@snx-v3/TokenIcon';
Expand All @@ -11,6 +22,8 @@ import { makeSearch, useParams } from '@snx-v3/useParams';
import { useWithdrawTimer } from '@snx-v3/useWithdrawTimer';
import { CRatioAmount } from '../CRatioBar/CRatioAmount';
import { CRatioBadge } from '../CRatioBar/CRatioBadge';
import { useAccountCollateral } from '../../../../lib/useAccountCollateral';
import lockIcon from './lock.svg';

export function PositionRow({
liquidityPosition,
Expand All @@ -20,8 +33,17 @@ export function PositionRow({
apr?: number;
}) {
const [params, setParams] = useParams();
useAccountCollateral({
accountId: params.accountId,
tokenAddress: liquidityPosition.collateralType.address,
});
const { network } = useNetwork();

const { data: accountCollateral } = useAccountCollateral({
accountId: params.accountId,
tokenAddress: liquidityPosition.collateralType?.address,
});

const isStataUSDC = useIsSynthStataUSDC({
tokenAddress: liquidityPosition.collateralType.tokenAddress,
customNetwork: network,
Expand Down Expand Up @@ -76,8 +98,31 @@ export function PositionRow({
</Td>
<Td border="none">
<Flex flexDirection="column" alignItems="flex-end">
<Text color="white" lineHeight="1.25rem" fontFamily="heading" fontSize="sm">
<Text
display="flex"
alignItems="center"
gap={2}
color="white"
lineHeight="1.25rem"
fontFamily="heading"
fontSize="sm"
>
<Amount prefix="$" value={liquidityPosition.collateralValue} />
<Tooltip
label={
<>
Including in &nbsp;
<Amount
value={accountCollateral?.totalLocked}
suffix={` ${liquidityPosition.collateralType?.displaySymbol}`}
showTooltip
/>
&nbsp; Escrow that cannot be unlocked until the unlocking date has been reached
</>
}
>
<Image src={lockIcon} />
</Tooltip>
</Text>
<Text color="gray.500" fontFamily="heading" fontSize="0.75rem" lineHeight="1rem">
<Amount
Expand All @@ -102,6 +147,7 @@ export function PositionRow({
prefix="$"
value={liquidityPosition.availableCollateral.mul(liquidityPosition.collateralPrice)}
/>

{liquidityPosition.availableCollateral.gt(0) && isRunning && (
<Tooltip label={`Withdrawal available in ${hours}H${minutes}M`}>
<TimeIcon />
Expand Down
4 changes: 4 additions & 0 deletions liquidity/ui/src/components/Positions/lock.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
29 changes: 23 additions & 6 deletions liquidity/ui/src/components/Withdraw/Withdraw.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { type PositionPageSchemaType, useParams } from '@snx-v3/useParams';
import { useSystemToken } from '@snx-v3/useSystemToken';
import { useWithdrawTimer } from '@snx-v3/useWithdrawTimer';
import React from 'react';
import { useAccountCollateral } from '../../../../lib/useAccountCollateral';

export function Withdraw({ isDebtWithdrawal = false }: { isDebtWithdrawal?: boolean }) {
const [params] = useParams<PositionPageSchemaType>();
Expand All @@ -39,12 +40,28 @@ export function Withdraw({ isDebtWithdrawal = false }: { isDebtWithdrawal?: bool
const { minutes, hours, isRunning } = useWithdrawTimer(params.accountId);
const unlockDate = !isLoadingDate ? accountCollateralUnlockDate : null;

const maxWithdrawable =
network?.preset === 'andromeda' && liquidityPosition
? liquidityPosition.availableCollateral.add(liquidityPosition.availableSystemToken)
: isDebtWithdrawal
? liquidityPosition?.availableSystemToken
: liquidityPosition?.availableCollateral;
const { data: accountCollateral } = useAccountCollateral({
accountId: params.accountId,
tokenAddress: collateralType?.address,
});

const maxWithdrawable = React.useMemo(() => {
if (isDebtWithdrawal && liquidityPosition) {
return liquidityPosition.availableSystemToken;
}
if (!isDebtWithdrawal && liquidityPosition && accountCollateral) {
const unlockedCollateral = liquidityPosition.availableCollateral.sub(
accountCollateral.totalLocked
);
if (unlockedCollateral.lte(0)) {
// should not be possible but just in case
return ZEROWEI;
}
return network?.preset === 'andromeda'
? unlockedCollateral.add(liquidityPosition.availableSystemToken)
: unlockedCollateral;
}
}, [accountCollateral, isDebtWithdrawal, liquidityPosition, network]);

return (
<Flex flexDirection="column" data-cy="withdraw form">
Expand Down
16 changes: 16 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5244,6 +5244,22 @@ __metadata:
languageName: unknown
linkType: soft

"@snx-v3/useAccountCollateral@workspace:liquidity/lib/useAccountCollateral":
version: 0.0.0-use.local
resolution: "@snx-v3/useAccountCollateral@workspace:liquidity/lib/useAccountCollateral"
dependencies:
"@snx-v3/tsHelpers": "workspace:*"
"@snx-v3/useBlockchain": "workspace:*"
"@snx-v3/useCoreProxy": "workspace:*"
"@snx-v3/withERC7412": "workspace:*"
"@synthetixio/wei": "npm:^2.74.4"
"@tanstack/react-query": "npm:^5.8.3"
debug: "npm:^4.3.7"
ethers: "npm:^5.7.2"
react: "npm:^18.2.0"
languageName: unknown
linkType: soft

"@snx-v3/useAccountCollateralUnlockDate@workspace:*, @snx-v3/useAccountCollateralUnlockDate@workspace:liquidity/lib/useAccountCollateralUnlockDate":
version: 0.0.0-use.local
resolution: "@snx-v3/useAccountCollateralUnlockDate@workspace:liquidity/lib/useAccountCollateralUnlockDate"
Expand Down