Skip to content

Commit

Permalink
chore: reinstate close logic in user position row
Browse files Browse the repository at this point in the history
  • Loading branch information
chambaz committed Nov 17, 2023
1 parent 986fab5 commit 8c8acb7
Showing 1 changed file with 61 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,61 @@ const UserPositionRow: FC<UserPositionRowProps> = ({ 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) {
Expand Down Expand Up @@ -140,15 +194,18 @@ const UserPositionRow: FC<UserPositionRowProps> = ({ activeBankInfo, marginfiAcc
setValue={setWithdrawOrRepayAmount}
maxValue={maxAmount}
maxDecimals={activeBankInfo.info.state.mintDecimals}
disabled={maxAmount === 0}
disabled={maxAmount === 0 || isDisabled}
onEnter={withdrawOrRepay}
/>
</TableCell>

<TableCell className="text-white font-aeonik p-0 border-none" align="right">
<div className="h-full w-full flex justify-end items-center pl-2 sm:px-2">
<UserPositionRowAction onClick={withdrawOrRepay} disabled={isDisabled}>
{activeBankInfo.position.isLending ? "Withdraw" : "Repay"}
<UserPositionRowAction
onClick={isDust ? closeBalance : withdrawOrRepay}
disabled={maxAmount === 0 || isDisabled}
>
{isDust ? "Close" : activeBankInfo.position.isLending ? "Withdraw" : "Repay"}
</UserPositionRowAction>
</div>
</TableCell>
Expand Down

0 comments on commit 8c8acb7

Please sign in to comment.