diff --git a/apps/marginfi-v2-ui/src/components/desktop/UserPositions/UserPositionRow/UserPositionRow.tsx b/apps/marginfi-v2-ui/src/components/desktop/UserPositions/UserPositionRow/UserPositionRow.tsx index 8bfe1ff2dd..b5505ccc0d 100644 --- a/apps/marginfi-v2-ui/src/components/desktop/UserPositions/UserPositionRow/UserPositionRow.tsx +++ b/apps/marginfi-v2-ui/src/components/desktop/UserPositions/UserPositionRow/UserPositionRow.tsx @@ -27,7 +27,61 @@ const UserPositionRow: FC = ({ activeBankInfo, marginfiAcc [activeBankInfo] ); - const isDisabled = useMemo(() => maxAmount === 0, [maxAmount]); + const isDust = useMemo(() => { + return uiToNative(activeBankInfo.position.amount, activeBankInfo.info.state.mintDecimals).isZero(); + }, [activeBankInfo]); + + const isDisabled = useMemo( + () => + (isDust && + uiToNative(activeBankInfo.userInfo.tokenAccount.balance, activeBankInfo.info.state.mintDecimals).isZero() && + !activeBankInfo.position.isLending) || + (!isDust && maxAmount === 0), + [isDust, activeBankInfo, maxAmount] + ); + + const closeBalance = useCallback(async () => { + if (!marginfiAccount) { + toast.error("marginfi account not ready."); + return; + } + + toast.loading("Closing dust balance", { + toastId: CLOSE_BALANCE_TOAST_ID, + }); + + try { + if (activeBankInfo.position.isLending) { + await marginfiAccount.withdraw(0, activeBankInfo.address, true); + } else { + await marginfiAccount.repay(0, activeBankInfo.address, true); + } + toast.update(CLOSE_BALANCE_TOAST_ID, { + render: "Closing 👍", + type: toast.TYPE.SUCCESS, + autoClose: 2000, + isLoading: false, + }); + } catch (error: any) { + toast.update(CLOSE_BALANCE_TOAST_ID, { + render: `Error while closing balance: ${error.message}`, + type: toast.TYPE.ERROR, + autoClose: 5000, + isLoading: false, + }); + console.log(`Error while closing balance`); + console.log(error); + } + + setWithdrawOrRepayAmount(0); + + try { + await reloadPositions(); + } catch (error: any) { + console.log("Error while reloading state"); + console.log(error); + } + }, [activeBankInfo, marginfiAccount, reloadPositions]); const withdrawOrRepay = useCallback(async () => { if (!marginfiAccount) { @@ -140,15 +194,18 @@ const UserPositionRow: FC = ({ activeBankInfo, marginfiAcc setValue={setWithdrawOrRepayAmount} maxValue={maxAmount} maxDecimals={activeBankInfo.info.state.mintDecimals} - disabled={maxAmount === 0} + disabled={maxAmount === 0 || isDisabled} onEnter={withdrawOrRepay} />
- - {activeBankInfo.position.isLending ? "Withdraw" : "Repay"} + + {isDust ? "Close" : activeBankInfo.position.isLending ? "Withdraw" : "Repay"}