Skip to content
Closed
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
5 changes: 5 additions & 0 deletions .changeset/dry-years-kick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@venusprotocol/evm": minor
---

expand geo-blocker feature to allow users to close restricted positions
48 changes: 48 additions & 0 deletions apps/evm/src/containers/AssetAccessor/__tests__/index.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,16 @@ const supplyProps: Omit<AssetAccessorProps, 'children'> = {
action: 'supply',
};

const withdrawProps: Omit<AssetAccessorProps, 'children'> = {
...borrowProps,
action: 'withdraw',
};

const repayProps: Omit<AssetAccessorProps, 'children'> = {
...borrowProps,
action: 'repay',
};

const fakeChildrenContent = 'Fake content';

const TestComponent = () => <>{fakeChildrenContent}</>;
Expand Down Expand Up @@ -116,6 +126,44 @@ describe('containers/AssetAccessor', () => {
expect(queryByText(fakeChildrenContent)).toBeNull();
});

it('renders children for a restricted asset when the user withdraws an existing supply position', async () => {
mockGetPool(
getCustomFakePool({
asset: {
isRestricted: true,
userSupplyBalanceCents: new BigNumber(1),
},
}),
);

const { getByText, queryByText } = renderComponent(
<AssetAccessor {...withdrawProps}>{() => <TestComponent />}</AssetAccessor>,
);

await waitFor(() => expect(getByText(fakeChildrenContent)).toBeInTheDocument());

expect(queryByText(en.assetAccessor.assetNotAvailable)).toBeNull();
});

it('renders children for a restricted asset when the user repays an existing borrow position', async () => {
mockGetPool(
getCustomFakePool({
asset: {
isRestricted: true,
userBorrowBalanceCents: new BigNumber(1),
},
}),
);

const { getByText, queryByText } = renderComponent(
<AssetAccessor {...repayProps}>{() => <TestComponent />}</AssetAccessor>,
);

await waitFor(() => expect(getByText(fakeChildrenContent)).toBeInTheDocument());

expect(queryByText(en.assetAccessor.assetNotAvailable)).toBeNull();
});

it('renders default token announcement if a disabled borrow action has no token announcement', async () => {
mockGetPool(
getCustomFakePool({
Expand Down
12 changes: 11 additions & 1 deletion apps/evm/src/containers/AssetAccessor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,17 @@ const AssetAccessor: React.FC<AssetAccessorProps> = ({
return <Spinner />;
}

if (asset.isRestricted) {
let isActionRestricted = asset.isRestricted;

// Allow user to close a position with an asset that's now restricted for them
if (
(action === 'withdraw' && asset.userSupplyBalanceCents?.isGreaterThan(0)) ||
(action === 'repay' && asset.userBorrowBalanceCents?.isGreaterThan(0))
) {
isActionRestricted = false;
}

if (isActionRestricted) {
return <NoticeWarning description={t('assetAccessor.assetNotAvailable')} />;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
HIGH_PRICE_IMPACT_THRESHOLD_PERCENTAGE,
MAXIMUM_PRICE_IMPACT_THRESHOLD_PERCENTAGE,
} from 'constants/swap';
import useDelegateApproval from 'hooks/useDelegateApproval';
import { useSimulateBalanceMutations } from 'hooks/useSimulateBalanceMutations';
import { defaultUserChainSettings, useUserChainSettings } from 'hooks/useUserChainSettings';
import { VError } from 'libs/errors';
Expand All @@ -31,13 +32,14 @@ import {
checkSubmitButtonIsEnabled,
} from 'pages/Market/OperationForm/__testUtils__/checkFns';
import { renderComponent } from 'testUtils/render';
import { type Asset, ChainId, type SwapQuote } from 'types';
import { type Asset, ChainId, type Pool, type SwapQuote } from 'types';
import { convertTokensToMantissa } from 'utilities';
import { RepayWithCollateralForm } from '..';
import { fakeAsset, fakePool } from '../../__testUtils__/fakeData';
import TEST_IDS from '../testIds';

vi.mock('hooks/useTokenApproval');
vi.mock('hooks/useDelegateApproval');

const fakeRepaidAsset = fakeAsset;
const fakeCollateralAsset = fakePool.assets[2];
Expand Down Expand Up @@ -84,6 +86,8 @@ const getLastUseGetSwapQuoteCallArgs = () =>

describe('RepayWithCollateralForm', () => {
beforeEach(() => {
mockRepayWithCollateral.mockReset();

(useUserChainSettings as Mock).mockReturnValue([
{
...defaultUserChainSettings,
Expand All @@ -96,6 +100,13 @@ describe('RepayWithCollateralForm', () => {
mutateAsync: mockRepayWithCollateral,
}));

(useDelegateApproval as Mock).mockReturnValue({
isDelegateApproved: true,
isDelegateApprovedLoading: false,
isUpdateDelegateStatusLoading: false,
updatePoolDelegateStatus: vi.fn(),
});

(useGetSwapQuote as Mock).mockImplementation(
(input: TrimmedGetSwapQuoteInput, { enabled }: UseQueryOptions) => ({
isLoading: false,
Expand Down Expand Up @@ -767,6 +778,64 @@ describe('RepayWithCollateralForm', () => {
expect(mockRepayWithCollateral.mock.calls[0]).toMatchSnapshot();
});

it('lets user use a restricted asset as collateral when repaying that same market', async () => {
const restrictedRepaidAsset: Asset = {
...fakeRepaidAsset,
isRestricted: true,
};
const restrictedPool: Pool = {
...fakePool,
assets: fakePool.assets.map(asset =>
asset.vToken.address === restrictedRepaidAsset.vToken.address
? {
...asset,
isRestricted: true,
}
: asset,
),
};

const { getByTestId, getByText, container } = renderComponent(
<RepayWithCollateralForm asset={restrictedRepaidAsset} pool={restrictedPool} />,
{
accountAddress: fakeAccountAddress,
},
);

selectToken({
container,
selectTokenTextFieldTestId: TEST_IDS.selectCollateralTokenTextField,
token: restrictedRepaidAsset.vToken.underlyingToken,
});

const collateralTokenInput = getByTestId(
getTokenTextFieldTestId({
parentTestId: TEST_IDS.selectCollateralTokenTextField,
}),
) as HTMLInputElement;

fireEvent.change(collateralTokenInput, {
target: { value: 1 },
});

await checkSubmitButtonIsEnabled({
textContent: en.operationForm.submitButtonLabel.repay,
});

fireEvent.click(getByText(en.operationForm.submitButtonLabel.repay));

await waitFor(() => expect(mockRepayWithCollateral).toHaveBeenCalledTimes(1));
expect(mockRepayWithCollateral.mock.calls[0]).toEqual([
expect.objectContaining({
amountMantissa: 1000000000000000000n,
vToken: expect.objectContaining({
address: restrictedRepaidAsset.vToken.address,
underlyingToken: restrictedRepaidAsset.vToken.underlyingToken,
}),
}),
]);
});

it('lets user repay full loan using a swap', async () => {
const { getByText, container } = renderComponent(
<RepayWithCollateralForm asset={fakeRepaidAsset} pool={fakePool} />,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,16 @@ export const RepayWithCollateralForm: React.FC<RepayWithCollateralFormProps> = (
// Sort by user supply balance
.sort((a, b) => compareBigNumbers(a.userSupplyBalanceCents, b.userSupplyBalanceCents, 'desc'))
.reduce<OptionalTokenBalance[]>((acc, asset) => {
// Allow user to use restricted collateral asset to repay the same asset
const isRestricted = asset.isRestricted && !areTokensEqual(asset.vToken, repaidAsset.vToken);

if (
// Skip vBNB
asset.vToken.symbol === 'vBNB' ||
// Skip tokens for which user has no supply
asset.userSupplyBalanceCents.isEqualTo(0) ||
// Skip restricted assets
asset.isRestricted
isRestricted
) {
return acc;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@ describe('useGetOperationFormTokenBalances', () => {
});
});

it('filters out restricted assets and preserves gated asset metadata', () => {
const allowedAsset = {
it('keeps the selected restricted asset, filters out other restricted assets, and preserves gated asset metadata', () => {
const restrictedUnderlyingAsset = {
...assetData[0],
disabledTokenActions: [],
isRestricted: false,
isRestricted: true,
isGated: false,
};
const gatedAsset = {
Expand All @@ -35,7 +35,7 @@ describe('useGetOperationFormTokenBalances', () => {
isRestricted: false,
isGated: true,
};
const restrictedAsset = {
const restrictedNonUnderlyingAsset = {
...assetData[3],
disabledTokenActions: [],
isRestricted: true,
Expand All @@ -45,7 +45,7 @@ describe('useGetOperationFormTokenBalances', () => {
(useGetPool as Mock).mockReturnValue({
data: {
pool: {
assets: [allowedAsset, gatedAsset, restrictedAsset],
assets: [restrictedUnderlyingAsset, gatedAsset, restrictedNonUnderlyingAsset],
},
},
});
Expand All @@ -54,7 +54,7 @@ describe('useGetOperationFormTokenBalances', () => {
useGetOperationFormTokenBalances({
poolComptrollerContractAddress: fakeAccountAddress,
accountAddress: fakeAccountAddress,
underlyingToken: allowedAsset.vToken.underlyingToken,
underlyingToken: restrictedUnderlyingAsset.vToken.underlyingToken,
isIntegratedSwapFeatureEnabled: true,
canWrapNativeToken: false,
action: 'supply',
Expand All @@ -63,7 +63,7 @@ describe('useGetOperationFormTokenBalances', () => {

expect(result.current.tokenBalances).toEqual([
expect.objectContaining({
token: allowedAsset.vToken.underlyingToken,
token: restrictedUnderlyingAsset.vToken.underlyingToken,
isGated: false,
balanceMantissa: expect.any(BigNumber),
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,10 @@ export const useGetOperationFormTokenBalances = ({

const isPaused = asset.disabledTokenActions.includes(action);

if (shouldIncludeTokenBalance && !isPaused && !asset.isRestricted) {
const isRestricted =
asset.isRestricted && !areTokensEqual(asset.vToken.underlyingToken, underlyingToken);

if (shouldIncludeTokenBalance && !isPaused && !isRestricted) {
tokenBalances.push({
token: asset.vToken.underlyingToken,
balanceMantissa: convertTokensToMantissa({
Expand Down
8 changes: 8 additions & 0 deletions apps/evm/src/pages/Trade/PairInfo/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@ export const PairInfo: React.FC<PairInfoProps> = ({ changePercentage, priceCents
acc.longAsset = asset;
}

if (asset.isRestricted) {
return acc;
}

const tokenBalance: OptionalTokenBalance = {
token: asset.vToken.underlyingToken,
isDeemed: asset.disabledTokenActions.includes('supply'),
Expand All @@ -99,6 +103,10 @@ export const PairInfo: React.FC<PairInfoProps> = ({ changePercentage, priceCents
acc.shortAsset = asset;
}

if (asset.isRestricted) {
return acc;
}

const tokenBalance: OptionalTokenBalance = {
token: asset.vToken.underlyingToken,
isDeemed: asset.disabledTokenActions.includes('borrow') || !asset.isBorrowable,
Expand Down
Loading
Loading