Skip to content

Commit

Permalink
fix: margin trading bug fix
Browse files Browse the repository at this point in the history
  • Loading branch information
deep-path committed Nov 18, 2024
1 parent 4266cfe commit 1d76006
Show file tree
Hide file tree
Showing 8 changed files with 98 additions and 31 deletions.
14 changes: 11 additions & 3 deletions components/HashResultModal/ModalWithCountdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,11 @@ const ModalWithCountdown = ({
const renderProgressBar = () => (
<div
className="rounded-sm"
style={{ width: `${progress}%`, backgroundColor: "#D2FF3A", height: "3px" }}
style={{
width: `${progress}%`,
backgroundColor: type == "Long" ? "#D2FF3A" : "#ff6ba9",
height: "3px",
}}
/>
);

Expand All @@ -88,7 +92,9 @@ const ModalWithCountdown = ({
<NearIconMini />
<span className="font-normal text-base px-2">{title}</span>
<div
className="text-sm text-toolTipBoxBorderColor rounded-sm p-1"
className={`text-sm ${
type == "Long" ? "text-toolTipBoxBorderColor" : "text-red-50"
} rounded-sm p-1`}
style={{ backgroundColor: "rgba(210, 255, 58, 0.1)" }}
>
{type} {positionSize.symbol}
Expand All @@ -104,7 +110,9 @@ const ModalWithCountdown = ({
<span className="text-gray-300">Position Size</span>
<span>
{positionSize.amount} {positionSize.symbol}
<span className="text-xs text-gray-300">({positionSize.usdValue})</span>
<span className="text-xs text-gray-300">
({(Number(positionSize.amount) * Number(price)).toFixed(6)})
</span>
</span>
</div>
<div className="absolute bottom-0 z-50 w-full left-0">{renderProgressBar()}</div>
Expand Down
11 changes: 8 additions & 3 deletions components/HashResultModal/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from "react";
import ReactDOM from "react-dom";
import { createRoot } from "react-dom/client";
import ModalWithCountdown from "./ModalWithCountdown";

interface ShowPositionResultParams {
Expand All @@ -15,6 +15,7 @@ interface ShowPositionResultParams {
}

let container: HTMLDivElement | null = null;
let root: ReturnType<typeof createRoot> | null = null;

export const showPositionResult = (params: ShowPositionResultParams) => {
if (params.transactionHashes) {
Expand All @@ -36,15 +37,19 @@ export const showPositionResult = (params: ShowPositionResultParams) => {
container = document.createElement("div");
container.id = "position-result-container";
document.body.appendChild(container);
root = createRoot(container);
}

const handleClose = () => {
if (root) {
root.unmount();
}
if (container) {
ReactDOM.unmountComponentAtNode(container);
container.remove();
container = null;
root = null;
}
};

ReactDOM.render(<ModalWithCountdown show onClose={handleClose} {...params} />, container);
root?.render(<ModalWithCountdown show onClose={handleClose} {...params} />);
};
1 change: 1 addition & 0 deletions interfaces/margin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export interface IMarginConfig {
open_position_fee_rate: number;
registered_dexes: { [dexId: string]: number };
registered_tokens: { [tokenId: string]: number };
max_active_user_margin_position: number;
}

export interface IMarginTradingPositionView {
Expand Down
2 changes: 2 additions & 0 deletions redux/marginConfigSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export const marginConfigSlice = createSlice({
open_position_fee_rate,
registered_dexes,
registered_tokens,
max_active_user_margin_position,
} = action.payload;
state.max_leverage_rate = max_leverage_rate;
state.pending_debt_scale = pending_debt_scale;
Expand All @@ -42,6 +43,7 @@ export const marginConfigSlice = createSlice({
state.open_position_fee_rate = open_position_fee_rate;
state.registered_dexes = registered_dexes;
state.registered_tokens = registered_tokens;
state.max_active_user_margin_position = max_active_user_margin_position;
});
},
});
Expand Down
2 changes: 2 additions & 0 deletions redux/marginConfigState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface IMarginConfigState {
registered_tokens: Record<string, number>;
status: Status;
fetchedAt: string | undefined;
max_active_user_margin_position: number;
}

export const initialState: IMarginConfigState = {
Expand All @@ -23,4 +24,5 @@ export const initialState: IMarginConfigState = {
registered_tokens: {},
status: undefined,
fetchedAt: undefined,
max_active_user_margin_position: 0,
};
16 changes: 16 additions & 0 deletions screens/Trading/components/TradingOperate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,14 @@ 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">
Expand Down Expand Up @@ -569,6 +577,14 @@ 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(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>
Expand Down
77 changes: 52 additions & 25 deletions screens/Trading/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,13 @@ import { useMarginConfigToken } from "../../hooks/useMarginConfig";
import { setCategoryAssets1, setCategoryAssets2 } from "../../redux/marginTrading";
import { useMarginAccount } from "../../hooks/useMarginAccount";
import { useAccountId, usePortfolioAssets } from "../../hooks/hooks";
import { useRouterQuery, getTransactionResult } from "../../utils/txhashContract";
import { useRouterQuery, getTransactionResult, parsedArgs } from "../../utils/txhashContract";
import { showPositionResult } from "../../components/HashResultModal";

init_env("dev");

const Trading = () => {
const marginConfig = useAppSelector(getMarginConfig);
const { query } = useRouterQuery();
const accountId = useAccountId();
const { marginAccountList, parseTokenValue, getAssetDetails, getAssetById } = useMarginAccount();
Expand All @@ -53,27 +54,6 @@ const Trading = () => {
};
let timer;

//
useEffect(() => {
if (router.query.transactionHashes) {
//
showPositionResult({
title: "Open Position",
type: "Long", // optional,"Long" 或 "Short"
price: "100", // optional,
transactionHashes: Array.isArray(router.query.transactionHashes)
? router.query.transactionHashes[0]
: (router.query.transactionHashes as string),
positionSize: {
// optional,
amount: "10",
symbol: "NEAR",
usdValue: "1000",
},
});
}
}, [router]);

// computed currentTokenCate1 dropdown
useEffect(() => {
if (id) {
Expand Down Expand Up @@ -168,11 +148,58 @@ const Trading = () => {
const results = await Promise.all(
txhash.map(async (txHash: string) => {
const result: any = await getTransactionResult(txHash);
console.log(result);
return { txHash };
const hasStorageDeposit = result.transaction.actions.some(
(action: any) => action?.FunctionCall?.method_name === "margin_execute_with_pyth",
);
return { txHash, result, hasStorageDeposit };
}),
);
console.log(results, ";rrrr");
results.forEach(({ txHash, result, hasStorageDeposit }: any) => {
if (hasStorageDeposit) {
// handleClaimTokenMobile({ level, count });
console.log(result);

const args = parsedArgs(result?.transaction?.actions?.[0]?.FunctionCall?.args || "");
const { actions } = JSON.parse(args || "");

// const ft_on_transfer_id = result?.receipts?.findIndex((r: any) =>
// r?.receipt?.Action?.actions?.some(
// (a: any) => a?.FunctionCall?.method_name === "margin_execute_with_pyth",
// ),
// );

// const ft_on_transfer_logs =
// result?.receipts_outcome?.[ft_on_transfer_id]?.outcome?.logs || "";
// const ft_on_transfer_log = ft_on_transfer_logs?.[ft_on_transfer_logs?.length - 1];
// const idx = ft_on_transfer_log?.indexOf("{");

// const parsed_ft_on_transfer_log = JSON.parse(ft_on_transfer_log.slice(idx) || "");
const isLong = actions[0]?.OpenPosition?.token_p_id == "wrap.testnet";
console.log(actions);
console.log(marginConfig);
showPositionResult({
title: "Open Position",
type: isLong ? "Long" : "Short",
price: (isLong
? Number(shrinkToken(actions[0]?.OpenPosition?.token_d_amount, 18)) /
Number(shrinkToken(actions[0]?.OpenPosition?.min_token_p_amount, 24))
: Number(shrinkToken(actions[0]?.OpenPosition?.min_token_p_amount, 18)) /
Number(shrinkToken(actions[0]?.OpenPosition?.token_d_amount, 24))
).toString(),
transactionHashes: Array.isArray(router.query.transactionHashes)
? router.query.transactionHashes[0]
: (router.query.transactionHashes as string),
positionSize: {
// optional,
amount: isLong
? shrinkToken(actions[0]?.OpenPosition?.min_token_p_amount, 24, 6)
: shrinkToken(actions[0]?.OpenPosition?.token_d_amount, 24, 6),
symbol: "NEAR",
usdValue: "1000",
},
});
}
});
} catch (error) {
console.error("Error processing transactions:", error);
}
Expand Down
6 changes: 6 additions & 0 deletions utils/txhashContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,9 @@ export function useRouterQuery() {

return { query, replaceQuery };
}

export const parsedArgs = (res: any) => {
const buff = Buffer.from(res, "base64");
const parsedData = buff.toString("ascii");
return parsedData;
};

0 comments on commit 1d76006

Please sign in to comment.