Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ import {
} from 'src/hooks/app-data-provider/useAppDataProvider';
import { useAssetCaps } from 'src/hooks/useAssetCaps';
import { useModalContext } from 'src/hooks/useModal';
import { useZeroLTVBlockingWithdraw } from 'src/hooks/useZeroLTVBlockingWithdraw';
import {
isBlockedByZeroLTV,
useZeroLTVBlockingWithdraw,
} from 'src/hooks/useZeroLTVBlockingWithdraw';
import { hasNonZeroEffectiveLtv } from 'src/utils/hfUtils';

import { GasEstimationError } from '../FlowCommons/GasEstimationError';
Expand Down Expand Up @@ -86,12 +89,7 @@ export const CollateralChangeModalContent = ({

// error handling
let blockingError: ErrorType | undefined = undefined;
if (
assetsBlockingWithdraw.length > 0 &&
!assetsBlockingWithdraw.some(
(r) => r.underlyingAsset.toLowerCase() === poolReserve.underlyingAsset.toLowerCase()
)
) {
if (isBlockedByZeroLTV(assetsBlockingWithdraw, userReserve)) {
blockingError = ErrorType.ZERO_LTV_WITHDRAW_BLOCKED;
} else if (valueToBigNumber(userReserve.underlyingBalance).eq(0)) {
blockingError = ErrorType.DO_NOT_HAVE_SUPPLIES_IN_THIS_CURRENCY;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export const ColalteralSwapDetails = ({ state }: { params: SwapParams; state: Sw
user,
toAmountAfterSlippage: valueToBigNumber(toAmount || '0'),
toAssetData: targetReserve,
toAssetUserData: userTargetReserve,
fromAssetType: 'collateral',
toAssetType: 'collateral',
eModes,
Expand Down
2 changes: 1 addition & 1 deletion src/components/transactions/Swap/errors/SwapErrors.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export const SwapErrors = ({
);
}

if (hasZeroLTVBlocking(state, assetsBlockingWithdraw)) {
if (hasZeroLTVBlocking(state, assetsBlockingWithdraw, extendedUser?.userReservesData ?? [])) {
return (
<ZeroLTVBlockingGuard
state={state}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { SxProps } from '@mui/material';
import React, { Dispatch, useEffect } from 'react';
import React, { Dispatch, useEffect, useMemo } from 'react';
import { useAppDataContext } from 'src/hooks/app-data-provider/useAppDataProvider';
import { FormattedUserReserves } from 'src/hooks/pool/useUserSummaryAndIncentives';
import { useZeroLTVBlockingWithdraw } from 'src/hooks/useZeroLTVBlockingWithdraw';

Expand All @@ -19,8 +20,13 @@ const getWithdrawnAsset = (state: SwapState) =>

// Mirrors `validateHFAndLtvzero` in aave-v3-origin SupplyLogic: when the user
// has any zero-LTV collateral enabled, every withdrawn aToken must itself have
// zero LTV.
export const hasZeroLTVBlocking = (state: SwapState, blockingReserves: FormattedUserReserves[]) => {
// zero LTV. The check only runs when the withdrawn aToken is enabled as
// collateral for the user (executeWithdraw / finalizeTransfer skip it otherwise).
export const hasZeroLTVBlocking = (
state: SwapState,
blockingReserves: FormattedUserReserves[],
userReserves: { underlyingAsset: string; usageAsCollateralEnabledOnUser: boolean }[]
) => {
if (blockingReserves.length === 0) return false;
// Direct DEX swaps don't touch Aave; the on-chain check never runs.
if (state.swapType === SwapType.Swap) return false;
Expand All @@ -29,6 +35,10 @@ export const hasZeroLTVBlocking = (state: SwapState, blockingReserves: Formatted
if (state.swapType === SwapType.DebtSwap) return false;

const withdrawnAsset = getWithdrawnAsset(state);
const withdrawnUserReserve = userReserves.find(
(userReserve) => userReserve.underlyingAsset.toLowerCase() === withdrawnAsset
);
if (withdrawnUserReserve && !withdrawnUserReserve.usageAsCollateralEnabledOnUser) return false;
// Withdrawing the LTV=0 asset itself is allowed by the protocol.
return !blockingReserves.some(
(userReserve) => userReserve.underlyingAsset.toLowerCase() === withdrawnAsset
Expand All @@ -47,10 +57,12 @@ export const ZeroLTVBlockingGuard = ({
isSwapFlowSelected: boolean;
}) => {
const assetsBlockingWithdraw = useZeroLTVBlockingWithdraw();
const { user } = useAppDataContext();
const userReserves = useMemo(() => user?.userReservesData ?? [], [user?.userReservesData]);
const withdrawnAsset = getWithdrawnAsset(state);

useEffect(() => {
const isBlocking = hasZeroLTVBlocking(state, assetsBlockingWithdraw);
const isBlocking = hasZeroLTVBlocking(state, assetsBlockingWithdraw, userReserves);

if (isBlocking) {
const isAlreadyBlockingError =
Expand Down Expand Up @@ -84,9 +96,9 @@ export const ZeroLTVBlockingGuard = ({
});
}
}
}, [assetsBlockingWithdraw, withdrawnAsset, state.swapType]);
}, [assetsBlockingWithdraw, userReserves, withdrawnAsset, state.swapType]);

if (hasZeroLTVBlocking(state, assetsBlockingWithdraw)) {
if (hasZeroLTVBlocking(state, assetsBlockingWithdraw, userReserves)) {
return <ZeroLTVBlockingError sx={{ mb: !isSwapFlowSelected ? 0 : 4, ...sx }} />;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import { hasZeroLTVBlocking } from '../ZeroLTVBlockingGuard';
jest.mock('src/hooks/useZeroLTVBlockingWithdraw', () => ({
useZeroLTVBlockingWithdraw: () => [],
}));
jest.mock('src/hooks/app-data-provider/useAppDataProvider', () => ({
useAppDataContext: () => ({}),
}));

/**
* Aave V3 Ethereum Core after the precautionary freeze (block 26302547): WETH is
Expand All @@ -21,6 +24,15 @@ const BLOCKING = [
{ underlyingAsset: WETH.toLowerCase(), reserve: { symbol: 'WETH' } },
] as unknown as FormattedUserReserves[];

const WBTC = '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599';

// The user's supplies with their on-user collateral flag.
const USER_RESERVES = [
{ underlyingAsset: WETH.toLowerCase(), usageAsCollateralEnabledOnUser: true },
{ underlyingAsset: WSTETH.toLowerCase(), usageAsCollateralEnabledOnUser: true },
{ underlyingAsset: WBTC.toLowerCase(), usageAsCollateralEnabledOnUser: false },
];

const token = (symbol: string, underlyingAddress: string) => ({ symbol, underlyingAddress });

// Swap reserves resolve in an effect after the first render, so they start unset.
Expand All @@ -37,17 +49,17 @@ const repayWithCollateral = (overrides: Record<string, unknown> = {}) =>

describe('hasZeroLTVBlocking', () => {
it('allows repaying with the zero-LTV collateral before reserves or a quote resolve', () => {
expect(hasZeroLTVBlocking(repayWithCollateral(), BLOCKING)).toBe(false);
expect(hasZeroLTVBlocking(repayWithCollateral(), BLOCKING, USER_RESERVES)).toBe(false);
});

it('allows repaying with wrapped native collateral shown with its native symbol', () => {
const state = repayWithCollateral({ sellAmountToken: token('ETH', WETH) });
expect(hasZeroLTVBlocking(state, BLOCKING)).toBe(false);
expect(hasZeroLTVBlocking(state, BLOCKING, USER_RESERVES)).toBe(false);
});

it('blocks repaying with collateral missing from the zero-LTV list', () => {
const state = repayWithCollateral({ destinationToken: token('wstETH', WSTETH) });
expect(hasZeroLTVBlocking(state, BLOCKING)).toBe(true);
expect(hasZeroLTVBlocking(state, BLOCKING, USER_RESERVES)).toBe(true);
});

it('reads the source token on collateral swap', () => {
Expand All @@ -56,6 +68,22 @@ describe('hasZeroLTVBlocking', () => {
sourceToken: token('ETH', WETH),
destinationToken: token('wstETH', WSTETH),
} as unknown as SwapState;
expect(hasZeroLTVBlocking(state, BLOCKING)).toBe(false);
expect(hasZeroLTVBlocking(state, BLOCKING, USER_RESERVES)).toBe(false);
});

it('allows swapping out of a supply that is not enabled as collateral', () => {
// executeWithdraw / finalizeTransfer only run validateHFAndLtvzero when the
// withdrawn aToken is enabled as collateral for the user.
const state = {
swapType: SwapType.CollateralSwap,
sourceToken: token('WBTC', WBTC),
destinationToken: token('wstETH', WSTETH),
} as unknown as SwapState;
expect(hasZeroLTVBlocking(state, BLOCKING, USER_RESERVES)).toBe(false);
});

it('allows repaying with collateral that is not enabled as collateral', () => {
const state = repayWithCollateral({ destinationToken: token('WBTC', WBTC) });
expect(hasZeroLTVBlocking(state, BLOCKING, USER_RESERVES)).toBe(false);
});
});
1 change: 1 addition & 0 deletions src/components/transactions/Swap/hooks/useFlowSelector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ const getHFAfterSwapParamsFromSwapType = (
toAmountAfterSlippage: state.buyAmountFormatted.toString(),
fromAssetData: state.sourceReserve.reserve,
toAssetData: state.destinationReserve.reserve,
toAssetUserData: toAssetUserReserve,
fromAssetUserData: fromAssetUserReserve,
fromAssetType: 'collateral',
toAssetType: 'collateral',
Expand Down
11 changes: 5 additions & 6 deletions src/components/transactions/Withdraw/WithdrawError.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import { valueToBigNumber } from '@aave/math-utils';
import { Trans } from '@lingui/macro';
import {
ComputedReserveData,
ComputedUserReserveData,
ExtendedFormattedUser,
} from 'src/hooks/app-data-provider/useAppDataProvider';
import { FormattedUserReserves } from 'src/hooks/pool/useUserSummaryAndIncentives';
import { useModalContext } from 'src/hooks/useModal';
import { isBlockedByZeroLTV } from 'src/hooks/useZeroLTVBlockingWithdraw';

enum ErrorType {
CAN_NOT_WITHDRAW_THIS_AMOUNT,
Expand All @@ -16,13 +18,15 @@ enum ErrorType {
interface WithdrawErrorProps {
assetsBlockingWithdraw: FormattedUserReserves[];
poolReserve: ComputedReserveData;
userReserve: ComputedUserReserveData;
healthFactorAfterWithdraw: BigNumber;
withdrawAmount: string;
user: ExtendedFormattedUser;
}
export const useWithdrawError = ({
assetsBlockingWithdraw,
poolReserve,
userReserve,
healthFactorAfterWithdraw,
withdrawAmount,
user,
Expand All @@ -33,12 +37,7 @@ export const useWithdrawError = ({
const unborrowedLiquidity = valueToBigNumber(poolReserve.unborrowedLiquidity);

if (!withdrawTxState.success && !withdrawTxState.txHash) {
if (
assetsBlockingWithdraw.length > 0 &&
!assetsBlockingWithdraw.some(
(r) => r.underlyingAsset.toLowerCase() === poolReserve.underlyingAsset.toLowerCase()
)
) {
if (isBlockedByZeroLTV(assetsBlockingWithdraw, userReserve)) {
blockingError = ErrorType.ZERO_LTV_WITHDRAW_BLOCKED;
} else if (
healthFactorAfterWithdraw.lt('1') &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export const WithdrawModalContent = ({
const { blockingError, errorComponent } = useWithdrawError({
assetsBlockingWithdraw,
poolReserve,
userReserve,
healthFactorAfterWithdraw,
withdrawAmount,
user,
Expand Down
45 changes: 45 additions & 0 deletions src/hooks/__tests__/useZeroLTVBlockingWithdraw.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { FormattedUserReserves } from 'src/hooks/pool/useUserSummaryAndIncentives';

import { isBlockedByZeroLTV } from '../useZeroLTVBlockingWithdraw';

jest.mock('src/hooks/app-data-provider/useAppDataProvider', () => ({}));
jest.mock('src/hooks/pool/useExtendedUserSummaryAndIncentives', () => ({}));
jest.mock('src/store/root', () => ({}));

/**
* Aave V3 Ethereum Core: tBTC is frozen with LTV 0 and enabled as collateral
* alongside WETH, against stablecoin debt. aWBTC received from a collateral swap
* sits with collateral disabled.
*/
const TBTC = '0x18084fbA666a33d37592fA2633fD49a74DD93a88';
const WETH = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2';
const WBTC = '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599';

const BLOCKING = [
{ underlyingAsset: TBTC.toLowerCase(), reserve: { symbol: 'tBTC' } },
] as unknown as FormattedUserReserves[];

const supply = (underlyingAsset: string, usageAsCollateralEnabledOnUser: boolean) => ({
underlyingAsset: underlyingAsset.toLowerCase(),
usageAsCollateralEnabledOnUser,
});

describe('isBlockedByZeroLTV', () => {
it('does not block without zero-LTV collateral', () => {
expect(isBlockedByZeroLTV([], supply(WETH, true))).toBe(false);
});

it('blocks removing other collateral while zero-LTV collateral is enabled', () => {
expect(isBlockedByZeroLTV(BLOCKING, supply(WETH, true))).toBe(true);
});

it('allows removing the zero-LTV collateral itself', () => {
expect(isBlockedByZeroLTV(BLOCKING, supply(TBTC, true))).toBe(false);
});

it('allows withdrawing or enabling a supply that is not enabled as collateral', () => {
// executeWithdraw only runs validateHFAndLtvzero for collateral, and enabling
// collateral never runs it.
expect(isBlockedByZeroLTV(BLOCKING, supply(WBTC, false))).toBe(false);
});
});
13 changes: 13 additions & 0 deletions src/hooks/useZeroLTVBlockingWithdraw.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,16 @@ export const useZeroLTVBlockingWithdraw = () => {

return zeroLTVBlockingWithdraw;
};

// Mirrors `validateHFAndLtvzero` in aave-v3-origin: while zero-LTV collateral is
// enabled, removing collateral is only allowed for a zero-LTV asset. Withdrawing a
// supply that is not enabled as collateral, or enabling one, never runs the check.
export const isBlockedByZeroLTV = (
blockingReserves: { underlyingAsset: string }[],
userReserve: { underlyingAsset: string; usageAsCollateralEnabledOnUser: boolean }
) =>
userReserve.usageAsCollateralEnabledOnUser &&
blockingReserves.length > 0 &&
!blockingReserves.some(
(r) => r.underlyingAsset.toLowerCase() === userReserve.underlyingAsset.toLowerCase()
);
69 changes: 69 additions & 0 deletions src/utils/__tests__/hfUtils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { ComputedUserReserve } from '@aave/math-utils';
import {
ComputedReserveData,
ExtendedFormattedUser,
} from 'src/hooks/app-data-provider/useAppDataProvider';

import { calculateHFAfterSwap } from '../hfUtils';

jest.mock('src/hooks/app-data-provider/useAppDataProvider', () => ({}));

// tBTC (frozen, LTV 0, LT 0.75) and WBTC (LTV 0.73, LT 0.78), both priced at 1.
const reserve = (underlyingAsset: string, baseLTVasCollateral: string, lt: string) =>
({
underlyingAsset,
baseLTVasCollateral,
reserveLiquidationThreshold: lt === '0' ? '0' : '7500',
formattedReserveLiquidationThreshold: lt,
formattedPriceInMarketReferenceCurrency: '1',
isIsolated: false,
eModes: [],
} as unknown as ComputedReserveData);

const TBTC = reserve('tbtc', '0', '0.75');
const WBTC = reserve('wbtc', '7300', '0.78');

// 100 tBTC collateral against 50 debt: HF 1.5.
const user = {
totalCollateralMarketReferenceCurrency: '100',
totalBorrowsMarketReferenceCurrency: '50',
currentLiquidationThreshold: '0.75',
userEmodeCategoryId: 0,
isInEmode: false,
isInIsolationMode: false,
} as unknown as ExtendedFormattedUser;

const swapTBTCToWBTC = (toAssetUserData?: Partial<ComputedUserReserve>) =>
calculateHFAfterSwap({
fromAmount: '10',
fromAssetData: TBTC,
fromAssetUserData: { usageAsCollateralEnabledOnUser: true } as ComputedUserReserve,
fromAssetType: 'collateral',
toAmountAfterSlippage: '10',
toAssetData: WBTC,
toAssetUserData: toAssetUserData as ComputedUserReserve | undefined,
toAssetType: 'collateral',
user,
eModes: {},
}).hfAfterSwap.toNumber();

describe('calculateHFAfterSwap', () => {
it('counts the received asset when its first supply auto-enables collateral', () => {
// (90 * 0.75 + 10 * 0.78) / 50
expect(swapTBTCToWBTC({ scaledATokenBalance: '0' })).toBeCloseTo(1.51);
});

it('counts the received asset when it is already enabled as collateral', () => {
expect(
swapTBTCToWBTC({ scaledATokenBalance: '1', usageAsCollateralEnabledOnUser: true })
).toBeCloseTo(1.51);
});

it('ignores the received asset when the existing supply has collateral disabled', () => {
// Supply only auto-enables collateral on the first supply, so the new aWBTC
// stays disabled: 90 * 0.75 / 50
expect(
swapTBTCToWBTC({ scaledATokenBalance: '1', usageAsCollateralEnabledOnUser: false })
).toBeCloseTo(1.35);
});
});
Loading
Loading