Skip to content

Commit

Permalink
borrow token select
Browse files Browse the repository at this point in the history
  • Loading branch information
xieqiancaosissi committed Dec 26, 2023
1 parent 6293aa1 commit 1419b52
Show file tree
Hide file tree
Showing 6 changed files with 87 additions and 68 deletions.
113 changes: 60 additions & 53 deletions components/Modal/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState } from "react";
import { useEffect, useState, createContext } from "react";
import { Modal as MUIModal, Typography, Box, Stack, useTheme } from "@mui/material";

import Decimal from "decimal.js";
Expand Down Expand Up @@ -40,6 +40,7 @@ import {
CollateralTypeSelectorRepay,
} from "./CollateralTypeSelector";

export const ModalContext = createContext(null) as any;
const Modal = () => {
const isOpen = useAppSelector(getModalStatus);
const accountId = useAppSelector(getAccountId);
Expand Down Expand Up @@ -124,60 +125,66 @@ const Modal = () => {
},
}}
>
<Box sx={{ p: ["20px", "20px"] }}>
{!accountId && <NotConnected />}
<ModalTitle asset={asset} onClose={handleClose} />
{action === "Borrow" ? (
<CollateralTypeSelectorBorrow
maxBorrowAmountPositions={maxBorrowAmountPositions}
selectedCollateralType={selectedCollateralType}
setSelectedCollateralType={setSelectedCollateralType}
/>
) : null}
{action === "Repay" ? (
<CollateralTypeSelectorRepay
repayPositions={repayPositions}
selectedCollateralType={selectedCollateralType}
setSelectedCollateralType={setSelectedCollateralType}
/>
) : null}
<RepayTab asset={asset} />
<Controls
amount={amount}
available={available}
action={action}
tokenId={tokenId}
asset={asset}
totalAvailable={available}
available$={available$}
/>
<div className="flex flex-col gap-4 mt-6">
<HealthFactor value={healthFactor} />
{action === "Repay" &&
isRepayFromDeposits &&
selectedCollateralType !== DEFAULT_POSITION ? (
<HealthFactor value={healthFactor_repay_lp} title="LP token Health Factor" />
<ModalContext.Provider
value={{
position: selectedCollateralType,
}}
>
<Box sx={{ p: ["20px", "20px"] }}>
{!accountId && <NotConnected />}
<ModalTitle asset={asset} onClose={handleClose} />
{action === "Borrow" ? (
<CollateralTypeSelectorBorrow
maxBorrowAmountPositions={maxBorrowAmountPositions}
selectedCollateralType={selectedCollateralType}
setSelectedCollateralType={setSelectedCollateralType}
/>
) : null}

<Rates rates={rates} />
{!canUseAsCollateral ? (
<CollateralTip />
) : (
<CollateralSwitch
action={action}
canUseAsCollateral={canUseAsCollateral}
tokenId={asset.tokenId}
{action === "Repay" ? (
<CollateralTypeSelectorRepay
repayPositions={repayPositions}
selectedCollateralType={selectedCollateralType}
setSelectedCollateralType={setSelectedCollateralType}
/>
)}
{/* <BorrowLimit from={maxBorrowValue} to="50" /> */}
</div>
<Alerts data={alerts} />
<Action
maxBorrowAmount={maxBorrowAmount}
healthFactor={healthFactor}
collateralType={selectedCollateralType}
/>
</Box>
) : null}
<RepayTab asset={asset} />
<Controls
amount={amount}
available={available}
action={action}
tokenId={tokenId}
asset={asset}
totalAvailable={available}
available$={available$}
/>
<div className="flex flex-col gap-4 mt-6">
<HealthFactor value={healthFactor} />
{action === "Repay" &&
isRepayFromDeposits &&
selectedCollateralType !== DEFAULT_POSITION ? (
<HealthFactor value={healthFactor_repay_lp} title="LP token Health Factor" />
) : null}

<Rates rates={rates} />
{!canUseAsCollateral ? (
<CollateralTip />
) : (
<CollateralSwitch
action={action}
canUseAsCollateral={canUseAsCollateral}
tokenId={asset.tokenId}
/>
)}
{/* <BorrowLimit from={maxBorrowValue} to="50" /> */}
</div>
<Alerts data={alerts} />
<Action
maxBorrowAmount={maxBorrowAmount}
healthFactor={healthFactor}
collateralType={selectedCollateralType}
/>
</Box>
</ModalContext.Provider>
</Wrapper>
</MUIModal>
);
Expand Down
10 changes: 8 additions & 2 deletions components/SelectToken/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { CloseIcon } from "../Modal/svg";
import { toggleUseAsCollateral } from "../../redux/appSlice";
import { IToken } from "../../interfaces/asset";
import { DEFAULT_POSITION } from "../../utils/config";
import { ModalContext } from "../Modal/index";

export type IAssetType = "borrow" | "supply";
type IBalance = { supply_balance?: string; borrow_balance?: string };
Expand All @@ -40,7 +41,7 @@ export default function SelectToken({
list.sort(sortByBalance);
setAssetList(list);
}
}, [Object.keys(updateAsset)?.length, rows?.length]);
}, [JSON.stringify(updateAsset), Object.keys(updateAsset)?.length, rows?.length]);

const sortByBalance = assetType === "supply" ? sortBySupplyBalance : sortByBorrowBalance;
function sortBySupplyBalance(b: IUIAsset, a: IUIAsset) {
Expand Down Expand Up @@ -198,15 +199,18 @@ function GetBalance({
asset,
updateAsset,
setUpdateAsset,
position,
}: {
asset: IUIAsset;
updateAsset: Record<string, IUIAsset>;
setUpdateAsset: any;
position: string;
}) {
const { symbol, tokenId } = asset;
const isWrappedNear = symbol === "NEAR";
const { supplyBalance, maxBorrowAmountPositions } = useUserBalance(tokenId, isWrappedNear);
const borrowBalance = maxBorrowAmountPositions[DEFAULT_POSITION]?.maxBorrowAmount?.toString(); // TODO
const borrowBalance =
maxBorrowAmountPositions[position || DEFAULT_POSITION]?.maxBorrowAmount?.toString();
updateAsset[tokenId] = {
...asset,
supply_balance: supplyBalance,
Expand All @@ -221,6 +225,7 @@ function GetBalance({
function TokenList() {
const { rows, updateAsset, setUpdateAsset, assetList, assetType, handleClose, selectRef } =
useContext(SelectTokenData) as any;
const { position } = useContext(ModalContext) as any;
return (
<>
{rows.map((asset: IUIAsset) => (
Expand All @@ -229,6 +234,7 @@ function TokenList() {
asset={asset}
updateAsset={updateAsset}
setUpdateAsset={setUpdateAsset}
position={position}
/>
))}
{assetList.map((asset: IUIAsset) => (
Expand Down
2 changes: 1 addition & 1 deletion hooks/useUserBalance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ export function useUserBalance(tokenId: string, isWrappedNear: boolean) {
} else {
supplyBalance = new Decimal(available || 0).toFixed();
}
// borrowBalance = Decimal.min(Math.max(0, maxBorrowAmount), availableLiquidity || 0).toFixed(); // TODO
// borrowBalance = Decimal.min(Math.max(0, maxBorrowAmount), availableLiquidity || 0).toFixed();
return { supplyBalance, maxBorrowAmountPositions };
}
22 changes: 16 additions & 6 deletions redux/selectors/getBorrowMaxAmount.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,37 @@
import { createSelector } from "@reduxjs/toolkit";

import Decimal from "decimal.js";
import { MAX_RATIO } from "../../store";
import { RootState } from "../store";
import { hasAssets } from "../utils";
import { hasAssets, transformAsset } from "../utils";
import { Assets } from "../assetState";
import { Portfolio } from "../accountState";
import { getAdjustedSum } from "./getWithdrawMaxAmount";
import { DEFAULT_POSITION } from "../../utils/config";
import { UIAsset } from "../../interfaces";

export const computeBorrowMaxAmount = (tokenId: string, assets: Assets, portfolio: Portfolio) => {
export const computeBorrowMaxAmount = (tokenId: string, assets: Assets, account, app) => {
const { portfolio } = account;
const asset = assets[tokenId];
const uiAsset: UIAsset = transformAsset(asset, account, assets, app);
return Object.keys(portfolio.positions)
.map((position: string) => {
const adjustedCollateralSum = getAdjustedSum("collateral", portfolio, assets, position);
const adjustedBorrowedSum = getAdjustedSum("borrowed", portfolio, assets, position);
const volatiliyRatio = asset.config.volatility_ratio || 0;
const price = asset.price?.usd || Infinity;
const maxBorrowPriced = adjustedCollateralSum
const maxBorrowPricedTemp = adjustedCollateralSum
.sub(adjustedBorrowedSum)
.mul(volatiliyRatio)
.div(MAX_RATIO)
.mul(95)
.div(100);
const maxBorrowAmount = maxBorrowPriced.div(price);
const maxBorrowAmountTemp = maxBorrowPricedTemp.div(price);
const maxBorrowAmount = Decimal.min(
Math.max(0, maxBorrowAmountTemp.toNumber()),
uiAsset.availableLiquidity || 0,
);
const maxBorrowPriced = maxBorrowAmountTemp.mul(price);
return {
[position]: {
maxBorrowAmount: Math.max(maxBorrowAmount.toNumber(), 0),
Expand All @@ -37,12 +46,13 @@ export const getBorrowMaxAmount = (tokenId: string) =>
createSelector(
(state: RootState) => state.assets,
(state: RootState) => state.account,
(assets, account) => {
(state: RootState) => state.app,
(assets, account, app) => {
if (!account.accountId || !tokenId)
return { [DEFAULT_POSITION]: { maxBorrowAmount: 0, maxBorrowValue: 0 } };
if (!hasAssets(assets))
return { [DEFAULT_POSITION]: { maxBorrowAmount: 0, maxBorrowValue: 0 } };
const maxBorrowAmount = computeBorrowMaxAmount(tokenId, assets.data, account.portfolio);
const maxBorrowAmount = computeBorrowMaxAmount(tokenId, assets.data, account, app);
return maxBorrowAmount;
},
);
6 changes: 2 additions & 4 deletions redux/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ export const transformAsset = (
shrinkToken(totalBorrowedD, asset.metadata.decimals + asset.config.extra_decimals),
);

// TODO: refactor: remove temp vars using ramda
const temp1 = new Decimal(asset.supplied.balance)
.plus(new Decimal(asset.reserved))
.plus(asset.prot_fee)
Expand All @@ -91,7 +90,6 @@ export const transformAsset = (
extraDecimals: 0,
};

// TODO: refactor this without conditional
if (account.accountId) {
const decimals = asset.metadata.decimals + asset.config.extra_decimals;
const supplied = Number(
Expand All @@ -100,13 +98,13 @@ export const transformAsset = (
const collateral = Number(
shrinkToken(
asset.isLpToken
? account.portfolio.positions[tokenId].collateral[tokenId]?.balance || 0
? account.portfolio.positions[tokenId]?.collateral?.[tokenId]?.balance || 0
: account.portfolio.collateral[tokenId]?.balance || 0,
decimals,
),
);
const borrowed = asset.isLpToken
? account.portfolio.positions[tokenId].borrowed[tokenId]?.balance || 0
? account.portfolio.positions[tokenId]?.borrowed?.[tokenId]?.balance || 0
: account.portfolio.borrowed[tokenId]?.balance || 0;
const available = account.balances[tokenId] || 0;
const availableNEAR = account.balances["near"] || 0;
Expand Down
2 changes: 0 additions & 2 deletions utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,6 @@ export const getBurrow = async ({
throw err;
}
};

/// TODO is this deprecated???
const call = async (
contract: Contract,
methodName: string,
Expand Down

0 comments on commit 1419b52

Please sign in to comment.