diff --git a/src/components/transactions/CollateralChange/CollateralChangeModalContent.tsx b/src/components/transactions/CollateralChange/CollateralChangeModalContent.tsx index b925c98914..28cf589793 100644 --- a/src/components/transactions/CollateralChange/CollateralChangeModalContent.tsx +++ b/src/components/transactions/CollateralChange/CollateralChangeModalContent.tsx @@ -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'; @@ -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; diff --git a/src/components/transactions/Swap/details/CollateralSwapDetails.tsx b/src/components/transactions/Swap/details/CollateralSwapDetails.tsx index be2a616a13..6f8e8749af 100644 --- a/src/components/transactions/Swap/details/CollateralSwapDetails.tsx +++ b/src/components/transactions/Swap/details/CollateralSwapDetails.tsx @@ -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, diff --git a/src/components/transactions/Swap/errors/SwapErrors.tsx b/src/components/transactions/Swap/errors/SwapErrors.tsx index 913ec47b7d..98eb359e51 100644 --- a/src/components/transactions/Swap/errors/SwapErrors.tsx +++ b/src/components/transactions/Swap/errors/SwapErrors.tsx @@ -86,7 +86,7 @@ export const SwapErrors = ({ ); } - if (hasZeroLTVBlocking(state, assetsBlockingWithdraw)) { + if (hasZeroLTVBlocking(state, assetsBlockingWithdraw, extendedUser?.userReservesData ?? [])) { return ( // 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; @@ -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 @@ -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 = @@ -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 ; } diff --git a/src/components/transactions/Swap/errors/shared/__tests__/ZeroLTVBlockingGuard.test.ts b/src/components/transactions/Swap/errors/shared/__tests__/ZeroLTVBlockingGuard.test.ts index 67a0d71e32..f472e1569d 100644 --- a/src/components/transactions/Swap/errors/shared/__tests__/ZeroLTVBlockingGuard.test.ts +++ b/src/components/transactions/Swap/errors/shared/__tests__/ZeroLTVBlockingGuard.test.ts @@ -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 @@ -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. @@ -37,17 +49,17 @@ const repayWithCollateral = (overrides: Record = {}) => 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', () => { @@ -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); }); }); diff --git a/src/components/transactions/Swap/hooks/useFlowSelector.ts b/src/components/transactions/Swap/hooks/useFlowSelector.ts index b5e71289f8..b76b65039d 100644 --- a/src/components/transactions/Swap/hooks/useFlowSelector.ts +++ b/src/components/transactions/Swap/hooks/useFlowSelector.ts @@ -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', diff --git a/src/components/transactions/Withdraw/WithdrawError.tsx b/src/components/transactions/Withdraw/WithdrawError.tsx index 39dde4cc37..2ee51850f1 100644 --- a/src/components/transactions/Withdraw/WithdrawError.tsx +++ b/src/components/transactions/Withdraw/WithdrawError.tsx @@ -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, @@ -16,6 +18,7 @@ enum ErrorType { interface WithdrawErrorProps { assetsBlockingWithdraw: FormattedUserReserves[]; poolReserve: ComputedReserveData; + userReserve: ComputedUserReserveData; healthFactorAfterWithdraw: BigNumber; withdrawAmount: string; user: ExtendedFormattedUser; @@ -23,6 +26,7 @@ interface WithdrawErrorProps { export const useWithdrawError = ({ assetsBlockingWithdraw, poolReserve, + userReserve, healthFactorAfterWithdraw, withdrawAmount, user, @@ -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') && diff --git a/src/components/transactions/Withdraw/WithdrawModalContent.tsx b/src/components/transactions/Withdraw/WithdrawModalContent.tsx index 455e358cb3..c6f788e359 100644 --- a/src/components/transactions/Withdraw/WithdrawModalContent.tsx +++ b/src/components/transactions/Withdraw/WithdrawModalContent.tsx @@ -84,6 +84,7 @@ export const WithdrawModalContent = ({ const { blockingError, errorComponent } = useWithdrawError({ assetsBlockingWithdraw, poolReserve, + userReserve, healthFactorAfterWithdraw, withdrawAmount, user, diff --git a/src/hooks/__tests__/useZeroLTVBlockingWithdraw.test.ts b/src/hooks/__tests__/useZeroLTVBlockingWithdraw.test.ts new file mode 100644 index 0000000000..42218469c3 --- /dev/null +++ b/src/hooks/__tests__/useZeroLTVBlockingWithdraw.test.ts @@ -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); + }); +}); diff --git a/src/hooks/useZeroLTVBlockingWithdraw.tsx b/src/hooks/useZeroLTVBlockingWithdraw.tsx index bc68ade066..25157689b4 100644 --- a/src/hooks/useZeroLTVBlockingWithdraw.tsx +++ b/src/hooks/useZeroLTVBlockingWithdraw.tsx @@ -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() + ); diff --git a/src/utils/__tests__/hfUtils.test.ts b/src/utils/__tests__/hfUtils.test.ts new file mode 100644 index 0000000000..b57c308024 --- /dev/null +++ b/src/utils/__tests__/hfUtils.test.ts @@ -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) => + 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); + }); +}); diff --git a/src/utils/hfUtils.ts b/src/utils/hfUtils.ts index a4131aaf2f..f28277be7f 100644 --- a/src/utils/hfUtils.ts +++ b/src/utils/hfUtils.ts @@ -20,6 +20,7 @@ export interface CalculateHFAfterSwapProps { fromAssetType: 'collateral' | 'debt' | 'none'; toAmountAfterSlippage: BigNumberValue; toAssetData: ComputedReserveData; + toAssetUserData?: ComputedUserReserve; user: ExtendedFormattedUser; toAssetType: 'collateral' | 'debt' | 'none'; eModes: Record; @@ -95,6 +96,7 @@ export function calculateHFAfterSwap({ fromAssetType, toAmountAfterSlippage, toAssetData, + toAssetUserData, user, toAssetType, eModes, @@ -126,12 +128,18 @@ export function calculateHFAfterSwap({ emodeEntry: toEmode, isEModeIsolated: !!eModes[user.userEmodeCategoryId]?.isolated, }); - const canAddToCollateral = - toAssetType === 'collateral' && + const isAutoEnabledOnSupply = hasToEffectiveLtv && ((!user.isInIsolationMode && !toAssetData.isIsolated) || (user.isInIsolationMode && user.isolatedReserve?.underlyingAsset === toAssetData.underlyingAsset)); + // Supply only auto-enables collateral on the first supply; an existing balance + // keeps the user's current collateral flag. + const hasExistingToSupply = + !!toAssetUserData && valueToBigNumber(toAssetUserData.scaledATokenBalance).gt(0); + const canAddToCollateral = + toAssetType === 'collateral' && + (hasExistingToSupply ? toAssetUserData.usageAsCollateralEnabledOnUser : isAutoEnabledOnSupply); const withdrawCollateralMR = canWithdrawFromCollateral ? valueToBigNumber(fromAmount).multipliedBy(