Skip to content

Commit

Permalink
fix: margin trading
Browse files Browse the repository at this point in the history
  • Loading branch information
deep-path committed Nov 25, 2024
1 parent 3afaa77 commit f41bcd6
Show file tree
Hide file tree
Showing 5 changed files with 142 additions and 37 deletions.
23 changes: 16 additions & 7 deletions screens/Trading/components/ConfirmMobile.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useState, createContext, useMemo } from "react";
import { Modal as MUIModal, Box, useTheme } from "@mui/material";
import { BeatLoader } from "react-spinners";
import { useAppDispatch } from "../../../redux/hooks";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import { Wrapper } from "../../../components/Modal/style";
import { DEFAULT_POSITION } from "../../../utils/config";
import { CloseIcon } from "../../../components/Modal/svg";
Expand All @@ -16,12 +16,18 @@ import {
RedSolidSubmitButton as RedSolidButton,
} from "../../../components/Modal/button";
import { shrinkToken } from "../../../store";
import { beautifyPrice } from "../../../utils/beautyNumbet";

const getTokenSymbolOnly = (assetId) => {
return assetId === "wNEAR" ? "NEAR" : assetId || "";
};

export const ModalContext = createContext(null) as any;
const ConfirmMobile = ({ open, onClose, action, confirmInfo }) => {
const dispatch = useAppDispatch();
const theme = useTheme();
const [selectedCollateralType, setSelectedCollateralType] = useState(DEFAULT_POSITION);
const { ReduxcategoryAssets1, ReduxcategoryAssets2 } = useAppSelector((state) => state.category);
const actionShowRedColor = action === "Long";
const [isDisabled, setIsDisabled] = useState(false);
const { marginConfigTokens } = useMarginConfigToken();
Expand All @@ -35,6 +41,7 @@ const ConfirmMobile = ({ open, onClose, action, confirmInfo }) => {
? getAssetById(confirmInfo.longOutputName?.token_id)
: getAssetById(confirmInfo.longInputName?.token_id),
);
const cateSymbol = getTokenSymbolOnly(ReduxcategoryAssets1.metadata.symbol);
const confirmOpenPosition = async () => {
// console.log(
// action == "Long"
Expand Down Expand Up @@ -128,7 +135,7 @@ const ConfirmMobile = ({ open, onClose, action, confirmInfo }) => {
actionShowRedColor ? "bg-primary text-primary" : "bg-red-50 text-red-50"
}`}
>
{action} NEAR {confirmInfo.rangeMount}X
{action} {cateSymbol} {confirmInfo.rangeMount}X
</div>
</div>
<div className="cursor-pointer">
Expand Down Expand Up @@ -163,8 +170,10 @@ const ConfirmMobile = ({ open, onClose, action, confirmInfo }) => {
{/* <div>${confirmInfo.entryPrice || "-"}</div> */}
<div>
$
{confirmInfo.tokenInAmount /
Number(shrinkToken(confirmInfo.estimateData?.min_amount_out, decimalsP))}
{beautifyPrice(
confirmInfo.tokenInAmount /
Number(shrinkToken(confirmInfo.estimateData?.min_amount_out, decimalsP)),
)}
</div>
</div>

Expand All @@ -189,7 +198,7 @@ const ConfirmMobile = ({ open, onClose, action, confirmInfo }) => {
</div>
<div className="flex items-center justify-between text-sm mb-4">
<div className="text-gray-300">Liq. Price</div>
<div>${confirmInfo.LiqPrice}</div>
<div>${beautifyPrice(confirmInfo.LiqPrice)}</div>
</div>
<div className="flex items-baseline justify-between text-sm mb-4">
<div className="text-gray-300 flex items-center">
Expand Down Expand Up @@ -250,7 +259,7 @@ const ConfirmMobile = ({ open, onClose, action, confirmInfo }) => {
{isDisabled ? (
<BeatLoader size={5} color="#14162B" />
) : (
` Confirm ${action} NEAR ${confirmInfo.rangeMount}X`
` Confirm ${action} ${cateSymbol} ${confirmInfo.rangeMount}X`
)}
</YellowSolidButton>
) : (
Expand All @@ -262,7 +271,7 @@ const ConfirmMobile = ({ open, onClose, action, confirmInfo }) => {
{isDisabled ? (
<BeatLoader size={5} color="#14162B" />
) : (
` Confirm ${action} NEAR ${confirmInfo.rangeMount}X`
` Confirm ${action} ${cateSymbol} ${confirmInfo.rangeMount}X`
)}
</RedSolidButton>
)}
Expand Down
63 changes: 39 additions & 24 deletions screens/Trading/components/TradingOperate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
YellowSolidSubmitButton as YellowSolidButton,
RedSolidSubmitButton as RedSolidButton,
} from "../../../components/Modal/button";
import { beautifyPrice } from "../../../utils/beautyNumbet";

// main components
const TradingOperate = () => {
Expand Down Expand Up @@ -63,6 +64,14 @@ const TradingOperate = () => {
const balance = useAppSelector(getAccountBalance);
const accountId = useAppSelector(getAccountId);

const getTokenSymbol = (assetId) => {
if (!assetId?.token_id) return "";
const asset = assets.data[assetId.token_id];
return asset?.metadata.symbol === "wNEAR" ? "NEAR" : asset?.metadata.symbol || "";
};
const getTokenSymbolOnly = (assetId) => {
return assetId === "wNEAR" ? "NEAR" : assetId || "";
};
// pools
const { simplePools, stablePools, stablePoolsDetail } = usePoolsData();

Expand Down Expand Up @@ -115,6 +124,7 @@ const TradingOperate = () => {
// }, 200);
// };

const cateSymbol = getTokenSymbolOnly(ReduxcategoryAssets1.metadata.symbol);
// slippageTolerance change ecent
useEffect(() => {
dispatch(setSlippageToleranceFromRedux(0.5));
Expand Down Expand Up @@ -394,7 +404,7 @@ const TradingOperate = () => {
<div className="flex justify-between items-center">
<div className="flex bg-dark-200 px-0.5 py-0.5 rounded-md cursor-pointer mr-3">
<div className={getTabClassName("long")} onClick={() => handleTabClick("long")}>
Long NEAR
Long {cateSymbol}
</div>
<div
className={
Expand All @@ -404,7 +414,7 @@ const TradingOperate = () => {
}
onClick={() => handleTabClick("short")}
>
Short NEAR
Short {cateSymbol}
</div>
</div>
{/* slip start */}
Expand Down Expand Up @@ -490,23 +500,26 @@ const TradingOperate = () => {
</div>
<RangeSlider defaultValue={rangeMount} action="Long" setRangeMount={setRangeMount} />
<div className="mt-5">
<div className="flex items-center justify-between text-sm mb-4">
<div className="text-gray-300">Minimum received</div>
<div className="text-right">
{Number(toInternationalCurrencySystem_number(longOutput)) *
(1 - slippageTolerance / 100)}{" "}
NEAR
</div>
</div>
<div className="flex items-center justify-between text-sm mb-4">
<div className="text-gray-300">Position Size</div>
<div className="text-right">
{toInternationalCurrencySystem_number(longOutput)} NEAR
{toInternationalCurrencySystem_number(longOutput)} {cateSymbol}
<span className="text-xs text-gray-300 ml-1.5">
(${toInternationalCurrencySystem_number(longOutputUsd)})
</span>
</div>
</div>

<div className="flex items-center justify-between text-sm mb-4">
<div className="text-gray-300">Minimum received</div>
<div className="text-right">
{beautifyPrice(
Number(toInternationalCurrencySystem_number(longOutput)) *
(1 - slippageTolerance / 100),
)}{" "}
{cateSymbol}
</div>
</div>
<div className="flex items-center justify-between text-sm mb-4">
<div className="text-gray-300">Liq. Price</div>
<div>${toInternationalCurrencySystem_number(LiqPrice)}</div>
Expand All @@ -515,7 +528,7 @@ const TradingOperate = () => {
<div className="text-gray-300">Fee</div>
<div className="flex items-center justify-center">
<p className="border-b border-dashed border-dark-800">{formatDecimal(Fee.fee)}</p>
NEAR
{cateSymbol}
<span className="text-xs text-gray-300 ml-1.5">
(${formatDecimal(Fee.fee * (Fee.price || 0))})
</span>
Expand Down Expand Up @@ -570,7 +583,7 @@ const TradingOperate = () => {
disabled={isDisabled}
onClick={handleConfirmButtonClick}
>
Long NEAR {rangeMount}x
Long {cateSymbol} {rangeMount}x
</YellowSolidButton>
{isConfirmModalOpen && (
<ConfirmMobile
Expand Down Expand Up @@ -635,23 +648,25 @@ const TradingOperate = () => {
</div>
<RangeSlider defaultValue={rangeMount} action="Short" setRangeMount={setRangeMount} />
<div className="mt-5">
<div className="flex items-center justify-between text-sm mb-4">
<div className="text-gray-300">Minimum received</div>
<div className="text-right">
{Number(toInternationalCurrencySystem_number(shortOutput)) *
(1 - slippageTolerance / 100)}{" "}
NEAR
</div>
</div>
<div className="flex items-center justify-between text-sm mb-4">
<div className="text-gray-300">Position Size</div>
<div>
{toInternationalCurrencySystem_number(shortOutput)} NEAR
{toInternationalCurrencySystem_number(shortOutput)} {cateSymbol}
<span className="text-xs text-gray-300 ml-1.5">
(${toInternationalCurrencySystem_number(shortOutputUsd)})
</span>
</div>
</div>
<div className="flex items-center justify-between text-sm mb-4">
<div className="text-gray-300">Minimum received</div>
<div className="text-right">
{beautifyPrice(
Number(toInternationalCurrencySystem_number(shortOutput)) *
(1 - slippageTolerance / 100),
)}{" "}
{cateSymbol}
</div>
</div>
<div className="flex items-center justify-between text-sm mb-4">
<div className="text-gray-300">Liq. Price</div>
<div>${toInternationalCurrencySystem_number(LiqPrice)}</div>
Expand All @@ -660,7 +675,7 @@ const TradingOperate = () => {
<div className="text-gray-300">Fee</div>
<div className="flex items-center justify-center">
<p className="border-b border-dashed border-dark-800">{formatDecimal(Fee.fee)}</p>
NEAR
{cateSymbol}
<span className="text-xs text-gray-300 ml-1.5">
(${formatDecimal(Fee.fee * (Fee.price || 0))})
</span>
Expand Down Expand Up @@ -715,7 +730,7 @@ const TradingOperate = () => {
disabled={isDisabled}
onClick={handleConfirmButtonClick}
>
Short NEAR {rangeMount}x
Short {cateSymbol} {rangeMount}x
</RedSolidButton>
{isConfirmModalOpen && (
<ConfirmMobile
Expand Down
4 changes: 2 additions & 2 deletions screens/Trading/components/tokenbox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ const TradingToken: React.FC<TradingTokenInter> = ({ tokenList, type, setOwnBanl
<div className="mx-1.5 text-base">
{selectedItem?.metadata?.symbol === "wNEAR" ? "NEAR" : selectedItem?.metadata?.symbol}
</div>
<TokenThinArrow />
{type === "cate2" && <TokenThinArrow />}
</div>

{type === "cate2" && (
Expand All @@ -138,7 +138,7 @@ const TradingToken: React.FC<TradingTokenInter> = ({ tokenList, type, setOwnBanl
</div>
)}
{/* */}
{showModal && (
{showModal && type === "cate2" && (
<div
className="absolute top-10 right-0 py-1.5 bg-dark-250 border border-dark-500 rounded-md z-80 w-52"
onMouseEnter={handleMouseEnter}
Expand Down
7 changes: 3 additions & 4 deletions screens/Trading/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ const Trading = () => {
const { marginAccountList, parseTokenValue, getAssetDetails, getAssetById } = useMarginAccount();
const { categoryAssets1, categoryAssets2 } = useMarginConfigToken();
const { ReduxcategoryAssets1, ReduxcategoryAssets2 } = useAppSelector((state) => state.category);

const router = useRouter();
const { id }: any = router.query;
const dispatch = useAppDispatch();
Expand Down Expand Up @@ -178,9 +177,9 @@ const Trading = () => {
? "NEAR"
: currentTokenCate1?.metadata?.symbol}
</p>
<TokenArrow />
{/* <TokenArrow /> */}
</div>
{showPopupCate1 && (
{/* {showPopupCate1 && (
<div
onMouseEnter={() => handleMouseEnter("1")}
onMouseLeave={() => handleMouseLeave("1")}
Expand Down Expand Up @@ -209,7 +208,7 @@ const Trading = () => {
</div>
))}
</div>
)}
)} */}
</div>
{/* cate2 */}
<div className="text-sm">
Expand Down
82 changes: 82 additions & 0 deletions utils/beautyNumbet.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
export const beautifyPrice = (num: number) => {
// 处理科学计数法的数字
let numStr = num.toString();
if (numStr.includes("e")) {
const [base, exp] = numStr.split("e");
const expNum = parseInt(exp, 10);
if (expNum < 0) {
const absExp = Math.abs(expNum);
numStr = `0.${"0".repeat(absExp - 1)}${base.replace(".", "")}`;
} else {
numStr = base.replace(".", "") + "0".repeat(expNum);
}
}

const arr = numStr.split(".");
const integerPart = arr[0];
const decimalPart = arr[1] || "";

if (!decimalPart) {
// 整数部分如果超过5位,只显示前5位
const digits = integerPart.slice(0, 5);
// 如果最后一位是0,则只取前4位
return (
<span key={num} className="animate-flipIn">
{digits.endsWith("0") ? digits.slice(0, 4) : digits}
</span>
);
}

if (+integerPart === 0) {
const nonZeroIndex = decimalPart.split("").findIndex((n) => +n !== 0);
if (nonZeroIndex <= 1) {
// 取5位有效数字,但如果最后一位是0则只取4位
let significantDigits = decimalPart.replace(/0+$/, "").slice(0, 5);
if (significantDigits.endsWith("0")) {
significantDigits = significantDigits.slice(0, 4);
}
return (
<span key={num} className="animate-flipIn">
{`0.${significantDigits}`}
</span>
);
}
const nonZeroPart = decimalPart.substring(nonZeroIndex);
let digits = nonZeroPart.slice(0, 4);
if (digits.endsWith("0")) {
digits = digits.slice(0, 3);
}
return (
<span key={num} className="animate-flipIn">
0.0
<span className="text-[8px] px-px">{nonZeroIndex}</span>
{digits}
</span>
);
}

// 整数部分不为0时
const floatPartLength = Math.max(5 - integerPart.length, 2);
let formattedDecimal = decimalPart.slice(0, floatPartLength).replace(/0+$/, "");

// 如果整数加小数的最后一位是0,则去掉
const fullNumber = integerPart + (formattedDecimal || "");
if (fullNumber.endsWith("0")) {
if (formattedDecimal) {
formattedDecimal = formattedDecimal.slice(0, -1);
} else {
return (
<span key={num} className="animate-flipIn">
{integerPart.slice(0, -1)}
</span>
);
}
}

return (
<span key={num} className="animate-flipIn">
{integerPart}
{formattedDecimal ? `.${formattedDecimal}` : ""}
</span>
);
};

0 comments on commit f41bcd6

Please sign in to comment.