Skip to content

Commit

Permalink
Merge branch 'add-margin-trading' into add-marginTrading-interface
Browse files Browse the repository at this point in the history
  • Loading branch information
deep-path committed Nov 18, 2024
2 parents 5b1a17e + 6c77ee6 commit 3ceea36
Show file tree
Hide file tree
Showing 12 changed files with 862 additions and 45 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,32 @@
import React, { useState, useEffect } from "react";
import { NearIcon, NearIconMini } from "../../MarginTrading/components/Icon";
import { CloseIcon } from "../../../components/Icons/Icons";
import { NearIcon, NearIconMini } from "../../screens/MarginTrading/components/Icon";
import { CloseIcon } from "../Icons/Icons";

const ModalWithCountdown = ({ show, onClose }) => {
interface PositionResultProps {
show: boolean;
onClose: () => void;
title?: string;
type?: "Long" | "Short";
price?: string;
positionSize?: {
amount: string;
symbol: string;
usdValue: string;
};
}

const ModalWithCountdown = ({
show,
onClose,
title = "Open Position",
type = "Long",
price = "$0.00",
positionSize = {
amount: "0",
symbol: "NEAR",
usdValue: "$0.00",
},
}: PositionResultProps) => {
const [isModalVisible, setIsModalVisible] = useState(false);
const [countdown, setCountdown] = useState(10);
const [progress, setProgress] = useState(100);
Expand Down Expand Up @@ -47,7 +71,11 @@ const ModalWithCountdown = ({ show, onClose }) => {
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 @@ -62,25 +90,29 @@ const ModalWithCountdown = ({ show, onClose }) => {
<div className="fc">
<div className="fc">
<NearIconMini />
<span className="font-normal text-base px-2">Open Position</span>
<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)" }}
>
Long Near
{type} {positionSize.symbol}
</div>
</div>
<div className="text-gray-1000 text-sm ml-auto">Filled</div>
</div>
<div className="fc justify-between text-sm font-normal">
<span className="text-gray-300">Price</span>
<span>$3.34</span>
<span>{price}</span>
</div>
<div className="fc justify-between text-sm font-normal">
<span className="text-gray-300">Position Size</span>
<span>
45.2435 NEAR
<span className="text-xs text-gray-300">($149.35)</span>
{positionSize.amount} {positionSize.symbol}
<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
55 changes: 55 additions & 0 deletions components/HashResultModal/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import React from "react";
import { createRoot } from "react-dom/client";
import ModalWithCountdown from "./ModalWithCountdown";

interface ShowPositionResultParams {
title?: string;
type?: "Long" | "Short";
price?: string;
transactionHashes?: string;
positionSize?: {
amount: string;
symbol: string;
usdValue: string;
};
}

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

export const showPositionResult = (params: ShowPositionResultParams) => {
if (params.transactionHashes) {
const shownTxs = localStorage.getItem("shownTransactions") || "[]";
const shownTxArray = JSON.parse(shownTxs);

if (shownTxArray.includes(params.transactionHashes)) {
return;
}

shownTxArray.push(params.transactionHashes);
if (shownTxArray.length > 100) {
shownTxArray.shift();
}
localStorage.setItem("shownTransactions", JSON.stringify(shownTxArray));
}

if (!container) {
container = document.createElement("div");
container.id = "position-result-container";
document.body.appendChild(container);
root = createRoot(container);
}

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

root?.render(<ModalWithCountdown show onClose={handleClose} {...params} />);
};
3 changes: 2 additions & 1 deletion interfaces/margin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ export interface IMarginConfig {
max_leverage_rate: number;
pending_debt_scale: number;
max_slippage_rate: number;
min_safty_buffer: number;
min_safety_buffer: number;
margin_debt_discount_rate: number;
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
6 changes: 4 additions & 2 deletions redux/marginConfigSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,22 @@ export const marginConfigSlice = createSlice({
max_leverage_rate,
pending_debt_scale,
max_slippage_rate,
min_safty_buffer,
min_safety_buffer,
margin_debt_discount_rate,
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;
state.max_slippage_rate = max_slippage_rate;
state.min_safty_buffer = min_safty_buffer;
state.min_safety_buffer = min_safety_buffer;
state.margin_debt_discount_rate = margin_debt_discount_rate;
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
6 changes: 4 additions & 2 deletions redux/marginConfigState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,26 @@ export interface IMarginConfigState {
max_leverage_rate: number;
pending_debt_scale: number;
max_slippage_rate: number;
min_safty_buffer: number;
min_safety_buffer: number;
margin_debt_discount_rate: number;
open_position_fee_rate: number;
registered_dexes: Record<string, number>;
registered_tokens: Record<string, number>;
status: Status;
fetchedAt: string | undefined;
max_active_user_margin_position: number;
}

export const initialState: IMarginConfigState = {
max_leverage_rate: 0,
pending_debt_scale: 0,
max_slippage_rate: 0,
min_safty_buffer: 0,
min_safety_buffer: 0,
margin_debt_discount_rate: 0,
open_position_fee_rate: 0,
registered_dexes: {},
registered_tokens: {},
status: undefined,
fetchedAt: undefined,
max_active_user_margin_position: 0,
};
6 changes: 3 additions & 3 deletions screens/Trading/components/ChangeCollateralMobile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -119,13 +119,13 @@ const ChangeCollateralMobile = ({ open, onClose, rowData, collateralTotal }) =>
(rowData.data.debt_cap *
((debt_assets_d?.unit_acc_hp_interest ?? 0) - rowData.data.uahpi_at_open)) /
10 ** 18;
const decrease_cap = total_cap * (marginConfigTokens.min_safty_buffer / 10000);
const denominator = sizeValueLong * (1 - marginConfigTokens.min_safty_buffer / 10000);
const decrease_cap = total_cap * (marginConfigTokens.min_safety_buffer / 10000);
const denominator = sizeValueLong * (1 - marginConfigTokens.min_safety_buffer / 10000);
const LiqPrice =
denominator !== 0
? (total_debt +
total_hp_fee +
(priceC * leverageC * marginConfigTokens.min_safty_buffer) / 10000 -
(priceC * leverageC * marginConfigTokens.min_safety_buffer) / 10000 -
priceC * leverageC) /
denominator
: 0;
Expand Down
6 changes: 3 additions & 3 deletions screens/Trading/components/Table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -243,14 +243,14 @@ const PositionRow = ({
const total_debt = leverageD * priceD;
const total_hp_fee =
(item.debt_cap * ((debt_assets_d?.unit_acc_hp_interest ?? 0) - item.uahpi_at_open)) / 10 ** 18;
// const decrease_cap = total_cap * (marginConfigTokens.min_safty_buffer / 10000);
const denominator = sizeValueLong * (1 - marginConfigTokens.min_safty_buffer / 10000);
// const decrease_cap = total_cap * (marginConfigTokens.min_safety_buffer / 10000);
const denominator = sizeValueLong * (1 - marginConfigTokens.min_safety_buffer / 10000);
// total_cap - decrease_cap === total_debt + total_hp_fee;
const LiqPrice =
denominator !== 0
? (total_debt +
total_hp_fee +
(priceC * leverageC * marginConfigTokens.min_safty_buffer) / 10000 -
(priceC * leverageC * marginConfigTokens.min_safety_buffer) / 10000 -
priceC * leverageC) /
denominator
: 0;
Expand Down
74 changes: 60 additions & 14 deletions screens/Trading/components/TradingOperate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ const TradingOperate = () => {
const [isDisabled, setIsDisabled] = useState(false);

//
const [longInput, setLongInput] = useState(0);
const [shortInput, setShortInput] = useState(0);
const [longInput, setLongInput] = useState("");
const [shortInput, setShortInput] = useState("");
const [longOutput, setLongOutput] = useState(0);
const [shortOutput, setShortOutput] = useState(0);

Expand Down Expand Up @@ -78,13 +78,13 @@ const TradingOperate = () => {
const initCateState = (tabString) => {
setLiqPrice(0);
setRangeMount(1);
if (tabString === "long") {
setShortInput(0);
if (tabString == "long") {
setShortInput("");
setShortInputUsd(0);
setShortOutput(0);
setShortOutputUsd(0);
} else {
setLongInput(0);
setLongInput("");
setLongInputUsd(0);
setLongOutput(0);
setLongOutputUsd(0);
Expand Down Expand Up @@ -276,25 +276,51 @@ const TradingOperate = () => {

let liqPriceX = 0;
if (rangeMount > 1) {
if (activeTab === "long") {
const k1 = longInput * rangeMount * (getAssetPrice(ReduxcategoryAssets2) as any);
const k2 = 1 - marginConfigTokens.min_safty_buffer / 10000;
liqPriceX = (k1 / k2 - longInput) / longOutput;
if (activeTab == "long") {
const k1 = Number(longInput) * rangeMount * (getAssetPrice(ReduxcategoryAssets2) as any);
const k2 = 1 - marginConfigTokens.min_safety_buffer / 10000;
liqPriceX = (k1 / k2 - Number(longInput)) / longOutput;
} else {
liqPriceX =
(((Number(shortInput) +
Number(shrinkToken(estimateData?.min_amount_out, decimalsC))) as any) *
rangeMount *
(getAssetPrice(ReduxcategoryAssets2) as any) *
(1 - marginConfigTokens.min_safty_buffer / 10000)) /
(1 - marginConfigTokens.min_safety_buffer / 10000)) /
shortOutput;
}
}

// const total_debt =
// (shrinkToken(ReduxcategoryAssets2.margin_debt.balance, decimalsD) as any) * priceD;
// const total_hp_fee =
// (ReduxcategoryAssets2.margin_debt.debt_cap * (unit_acc_hp_interest - uahpi_at_open)) /
// 10 ** 18;

// const numerator =
// total_debt +
// total_hp_fee -
// (shrinkToken(ReduxcategoryAssets1.margin_debt.balance, decimalsD) as any) *
// priceC *
// (1 - marginConfigTokens.min_safety_buffer / 10000);

// const denominator =
// estimateData?.min_amount_out * (1 - marginConfigTokens.min_safety_buffer / 10000);

console.log(marginConfigTokens, ReduxcategoryAssets2, ReduxcategoryAssets1);

setLiqPrice(liqPriceX);
}
}, [longOutput, shortOutput]);

const Fee = useMemo(() => {
console.log(ReduxcategoryAssets1, ReduxcategoryAssets2);
return {
fee: (Number(longInput || shortInput) * config.open_position_fee_rate) / 10000,
price: getAssetPrice(ReduxcategoryAssets1),
};
}, [longInput, shortInput, ReduxcategoryAssets1]);

function getAssetPrice(categoryId) {
return categoryId ? assets.data[categoryId["token_id"]].price?.usd : 0;
}
Expand Down Expand Up @@ -459,6 +485,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 All @@ -475,9 +509,11 @@ const TradingOperate = () => {
<div className="flex items-center justify-between text-sm mb-4">
<div className="text-gray-300">Fee</div>
<div className="flex items-center justify-center">
<p className="border-b border-dashed border-dark-800">0.26</p>
<p className="border-b border-dashed border-dark-800">{Fee.fee}</p>
NEAR
<span className="text-xs text-gray-300 ml-1.5">($0.89)</span>
<span className="text-xs text-gray-300 ml-1.5">
(${Fee.fee * (Fee.price || 0)})
</span>
</div>
</div>
<div className="flex items-baseline justify-between text-sm mb-4">
Expand Down Expand Up @@ -594,6 +630,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(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>
Expand All @@ -610,9 +654,11 @@ const TradingOperate = () => {
<div className="flex items-center justify-between text-sm mb-4">
<div className="text-gray-300">Fee</div>
<div className="flex items-center justify-center">
<p className="border-b border-dashed border-dark-800">0.26</p>
<p className="border-b border-dashed border-dark-800">{Fee.fee}</p>
NEAR
<span className="text-xs text-gray-300 ml-1.5">($0.89)</span>
<span className="text-xs text-gray-300 ml-1.5">
(${Fee.fee * (Fee.price || 0)})
</span>
</div>
</div>
<div className="flex items-baseline justify-between text-sm mb-4">
Expand Down
Loading

0 comments on commit 3ceea36

Please sign in to comment.