Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Futures mobile fixes #1175

Merged
merged 24 commits into from
Aug 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
292908d
Remove redundant div and share data between tables
koredefashokun Jul 25, 2022
b88aa69
Remodel confirmation states
koredefashokun Jul 25, 2022
da296f6
Fix conflicts
koredefashokun Jul 25, 2022
0e450e1
Add position side stuff
koredefashokun Jul 25, 2022
80a357c
Fix next price drawer row height
koredefashokun Jul 26, 2022
d2723b1
Add stop-gap solution for leaderboard on mobile
koredefashokun Jul 26, 2022
4c31aca
Merge branch 'dev' into futures-mobile-fixes
koredefashokun Jul 26, 2022
e95068c
Fix formatNumber error
koredefashokun Jul 27, 2022
df1f8c1
tab button size fix
asherism Jul 27, 2022
3fb43f6
Bottom-align mobile settings and menu
koredefashokun Jul 28, 2022
60c99c8
Fix pane height issue (hacky)
koredefashokun Jul 28, 2022
00c62a5
Merge remote-tracking branch 'origin/dev' into futures-mobile-fixes
koredefashokun Jul 29, 2022
ef028b1
Fix height of OverviewTabs
koredefashokun Jul 29, 2022
a193986
Set correct background for OpenPostionContainer
koredefashokun Jul 29, 2022
e5837ee
Merge remote-tracking branch 'origin/dev' into futures-mobile-fixes
koredefashokun Jul 29, 2022
44a5766
Refactor things
koredefashokun Jul 30, 2022
a71b35b
Fix padding issue with Pane component
koredefashokun Jul 30, 2022
a5413c5
Left-align the oracle/entry price
koredefashokun Jul 31, 2022
7098ccc
Make the mobile FuturesPositionsTable somewhat responsive
koredefashokun Jul 31, 2022
3cb544b
Merge remote-tracking branch 'origin/dev' into futures-mobile-fixes
koredefashokun Aug 1, 2022
ab5c239
Add truncation for skew values
koredefashokun Aug 2, 2022
f40a70c
Add more width for leftmost row on mobile FuturesPositionTable
koredefashokun Aug 2, 2022
5903417
Fix issues with PR
koredefashokun Aug 2, 2022
586ab40
Remove spacing on sides of chart
koredefashokun Aug 2, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions constants/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,6 @@ export const MAX_TIMESTAMP: number = 8640000000000000;

// leverage adjustment
export const DEFAULT_NP_LEVERAGE_ADJUSTMENT: number = 0.9975;

// for mobile leaderboard
export const DEFAULT_LEADERBOARD_ROWS = 20;
2 changes: 2 additions & 0 deletions contexts/RefetchContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import useGetFuturesOpenOrders from 'queries/futures/useGetFuturesOpenOrders';
import useGetFuturesPositionForMarket from 'queries/futures/useGetFuturesPositionForMarket';
import useGetFuturesPositionForMarkets from 'queries/futures/useGetFuturesPositionForMarkets';
import useGetFuturesPotentialTradeDetails from 'queries/futures/useGetFuturesPotentialTradeDetails';
import useExchangeRatesQuery from 'queries/rates/useExchangeRatesQuery';
import useSynthBalances from 'queries/synths/useSynthBalances';

type RefetchType = 'modify-position' | 'new-order' | 'close-position' | 'margin-change';
Expand All @@ -23,6 +24,7 @@ export const RefetchProvider: React.FC = ({ children }) => {
const positionQuery = useGetFuturesPositionForMarket();
const positionsQuery = useGetFuturesPositionForMarkets();
const marketsQuery = useGetFuturesMarkets();
useExchangeRatesQuery({ refetchInterval: 15000 });
useGetFuturesPotentialTradeDetails();

const handleRefetch = (refetchType: RefetchType, timeout?: number) => {
Expand Down
48 changes: 6 additions & 42 deletions hooks/useFuturesData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,21 @@ import Wei, { wei } from '@synthetixio/wei';
import { useRefetchContext } from 'contexts/RefetchContext';
import { ethers } from 'ethers';
import { useRouter } from 'next/router';
import React, { useState, useMemo, useEffect } from 'react';
import { useRecoilState, useRecoilValue } from 'recoil';
import React, { useState, useEffect } from 'react';
import { useSetRecoilState, useRecoilState, useRecoilValue } from 'recoil';

import { Synths } from 'constants/currency';
import Connector from 'containers/Connector';
import TransactionNotifier from 'containers/TransactionNotifier';
import { KWENTA_TRACKING_CODE } from 'queries/futures/constants';
import { getFuturesMarketContract } from 'queries/futures/utils';
import useExchangeRatesQuery from 'queries/rates/useExchangeRatesQuery';
import { PositionSide } from 'sections/futures/types';
import {
currentMarketState,
feeCostState,
leverageSideState,
leverageState,
leverageValueCommittedState,
marketAssetRateState,
marketInfoState,
marketKeyState,
maxLeverageState,
orderTypeState,
positionState,
Expand All @@ -30,7 +27,6 @@ import {
tradeSizeSUSDState,
} from 'store/futures';
import { gasSpeedState, walletAddressState } from 'store/wallet';
import { newGetExchangeRatesForCurrencies } from 'utils/currencies';
import { zeroBN } from 'utils/formatters/number';
import { getDisplayAsset } from 'utils/futures';
import logError from 'utils/logError';
Expand All @@ -39,22 +35,20 @@ const DEFAULT_MAX_LEVERAGE = wei(10);

const useFuturesData = () => {
const walletAddress = useRecoilValue(walletAddressState);
const exchangeRatesQuery = useExchangeRatesQuery();
const router = useRouter();
const { synthetixjs } = Connector.useContainer();
const { useSynthetixTxn, useEthGasPriceQuery } = useSynthetixQueries();
const { monitorTransaction } = TransactionNotifier.useContainer();
const { handleRefetch } = useRefetchContext();

const marketAsset = useRecoilValue(currentMarketState);
const marketKey = useRecoilValue(marketKeyState);

const ethGasPriceQuery = useEthGasPriceQuery();

const [leverage, setLeverage] = useRecoilState(leverageState);
const [tradeSize, setTradeSize] = useRecoilState(tradeSizeState);
const [, setTradeSizeSUSD] = useRecoilState(tradeSizeSUSDState);
const [, setFeeCost] = useRecoilState(feeCostState);
const setTradeSizeSUSD = useSetRecoilState(tradeSizeSUSDState);
const setFeeCost = useSetRecoilState(feeCostState);
const leverageSide = useRecoilValue(leverageSideState);
const orderType = useRecoilValue(orderTypeState);
const sizeDelta = useRecoilValue(sizeDeltaState);
Expand All @@ -67,31 +61,14 @@ const useFuturesData = () => {
const [dynamicFee, setDynamicFee] = useState<Wei | null>(null);
const [error, setError] = useState<string | null>(null);

const exchangeRates = useMemo(() => exchangeRatesQuery.data ?? null, [exchangeRatesQuery.data]);

const marketAssetRate = useMemo(
() => newGetExchangeRatesForCurrencies(exchangeRates, marketKey, Synths.sUSD),
[exchangeRates, marketKey]
);
const marketAssetRate = useRecoilValue(marketAssetRateState);

const positionLeverage = position?.position?.leverage ?? wei(0);
const positionSide = position?.position?.side;
const marketMaxLeverage = market?.maxLeverage ?? DEFAULT_MAX_LEVERAGE;

const maxMarketValueUSD = market?.marketLimit ?? wei(0);
const marketSize = market?.marketSize ?? wei(0);
const marketSkew = market?.marketSkew ?? wei(0);

const gasPrice = ethGasPriceQuery?.data?.[gasSpeed];

const isMarketCapReached = useMemo(
() =>
leverageSide === PositionSide.LONG
? marketSize.add(marketSkew).div('2').abs().mul(marketAssetRate).gte(maxMarketValueUSD)
: marketSize.sub(marketSkew).div('2').abs().mul(marketAssetRate).gte(maxMarketValueUSD),
[leverageSide, marketSize, marketSkew, marketAssetRate, maxMarketValueUSD]
);

const onTradeAmountChange = React.useCallback(
(value: string, fromLeverage: boolean = false) => {
const size = fromLeverage ? (value === '' ? '' : wei(value).toNumber().toString()) : value;
Expand Down Expand Up @@ -199,16 +176,6 @@ const useFuturesData = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [orderTxn.hash]);

const placeOrderTranslationKey = React.useMemo(() => {
if (orderType === 1) return 'futures.market.trade.button.place-next-price-order';
if (!!position?.position) return 'futures.market.trade.button.modify-position';
return !position?.remainingMargin || position.remainingMargin.lt('50')
? 'futures.market.trade.button.deposit-margin-minimum'
: isMarketCapReached
? 'futures.market.trade.button.oi-caps-reached'
: 'futures.market.trade.button.open-position';
}, [position, orderType, isMarketCapReached]);

useEffect(() => {
const getOrderFee = async () => {
if (
Expand Down Expand Up @@ -260,13 +227,10 @@ const useFuturesData = () => {
marketAssetRate,
maxLeverageValue,
position,
placeOrderTranslationKey,
positionLeverage,
positionSide,
marketMaxLeverage,
error,
dynamicFee,
isMarketCapReached,
marketAsset,
market,
orderTxn,
Expand Down
4 changes: 2 additions & 2 deletions queries/futures/useGetFuturesOpenOrders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Wei from '@synthetixio/wei';
import { utils as ethersUtils } from 'ethers';
import request, { gql } from 'graphql-request';
import { useQuery, UseQueryOptions } from 'react-query';
import { useRecoilState, useRecoilValue } from 'recoil';
import { useSetRecoilState, useRecoilValue } from 'recoil';

import { ETH_UNIT } from 'constants/network';
import QUERY_KEYS from 'constants/queryKeys';
Expand All @@ -20,7 +20,7 @@ const useGetFuturesOpenOrders = (options?: UseQueryOptions<any>) => {
const walletAddress = useRecoilValue(walletAddressState);
const futuresEndpoint = getFuturesEndpoint(network);
const marketInfo = useRecoilValue(marketInfoState);
const [, setOpenOrders] = useRecoilState(openOrdersState);
const setOpenOrders = useSetRecoilState(openOrdersState);

return useQuery<any[]>(
QUERY_KEYS.Futures.OpenOrders(network.id, walletAddress),
Expand Down
8 changes: 4 additions & 4 deletions queries/futures/useGetFuturesPositionForMarkets.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { utils as ethersUtils } from 'ethers';
import { useQuery, UseQueryOptions } from 'react-query';
import { useRecoilState, useRecoilValue } from 'recoil';
import { useSetRecoilState, useRecoilValue } from 'recoil';

import QUERY_KEYS from 'constants/queryKeys';
import Connector from 'containers/Connector';
Expand All @@ -12,17 +12,17 @@ import { MarketKeyByAsset } from 'utils/futures';
import { FuturesPosition } from './types';
import { mapFuturesPosition, getFuturesMarketContract } from './utils';

const useGetFuturesPositionForMarkets = (options?: UseQueryOptions<FuturesPosition[] | []>) => {
const useGetFuturesPositionForMarkets = (options?: UseQueryOptions<FuturesPosition[]>) => {
const isAppReady = useRecoilValue(appReadyState);
const isL2 = useRecoilValue(isL2State);
const network = useRecoilValue(networkState);
const walletAddress = useRecoilValue(walletAddressState);
const { synthetixjs } = Connector.useContainer();
const [, setFuturesPositions] = useRecoilState(positionsState);
const setFuturesPositions = useSetRecoilState(positionsState);
const futuresMarkets = useRecoilValue(futuresMarketsState);
const assets = futuresMarkets.map(({ asset }) => asset);

return useQuery<FuturesPosition[] | []>(
return useQuery<FuturesPosition[]>(
QUERY_KEYS.Futures.MarketsPositions(network.id, walletAddress, assets || []),
async () => {
if (!assets || (walletAddress && !isL2)) {
Expand Down
6 changes: 5 additions & 1 deletion queries/rates/useExchangeRatesQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import {
import { wei } from '@synthetixio/wei';
import { BigNumberish, ethers } from 'ethers';
import { useQuery, UseQueryOptions } from 'react-query';
import { useRecoilValue } from 'recoil';
import { useRecoilValue, useSetRecoilState } from 'recoil';

import ROUTES from 'constants/routes';
import Connector from 'containers/Connector';
import { appReadyState } from 'store/app';
import { ratesState } from 'store/futures';
import { networkState } from 'store/wallet';

import { Rates } from './types';
Expand All @@ -29,6 +30,7 @@ const useExchangeRatesQuery = (options?: UseQueryOptions<Rates>) => {
const network = useRecoilValue(networkState);
const { synthetixjs: snxjs, defaultSynthetixjs } = Connector.useContainer();
const synthetixjs = window.location.pathname === ROUTES.Home.Root ? defaultSynthetixjs : snxjs;
const setRates = useSetRecoilState(ratesState);

return useQuery<Rates>(
['rates', 'exchangeRates2', network.id],
Expand All @@ -54,6 +56,8 @@ const useExchangeRatesQuery = (options?: UseQueryOptions<Rates>) => {
}
});

setRates(exchangeRates);

return exchangeRates;
},
{
Expand Down
17 changes: 13 additions & 4 deletions sections/dashboard/FuturesPositionsTable/FuturesPositionsTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -281,8 +281,10 @@ const FuturesPositionsTable: FC<FuturesPositionTableProps> = ({
<MobileOnlyView>
<OpenPositionsHeader>
<div>{t('dashboard.overview.futures-positions-table.mobile.market')}</div>
<div>{t('dashboard.overview.futures-positions-table.mobile.price')}</div>
<div>{t('dashboard.overview.futures-positions-table.mobile.pnl')}</div>
<OpenPositionsRightHeader>
<div>{t('dashboard.overview.futures-positions-table.mobile.price')}</div>
<div>{t('dashboard.overview.futures-positions-table.mobile.pnl')}</div>
</OpenPositionsRightHeader>
</OpenPositionsHeader>
<div style={{ margin: '0 15px' }}>
{data.length === 0 ? (
Expand Down Expand Up @@ -360,18 +362,25 @@ const MarketContainer = styled.div`
const OpenPositionsHeader = styled.div`
display: flex;
justify-content: space-between;
margin: 15px;
margin: 15px 15px 8px;
padding: 0 10px;

& > div {
color: ${(props) => props.theme.colors.selectedTheme.gray};
}

& > div:first-child {
width: 150px;
width: 125px;
margin-right: 30px;
}
`;

const OpenPositionsRightHeader = styled.div`
display: flex;
flex: 1;
justify-content: space-between;
`;

const NoPositionsText = styled.div`
color: ${(props) => props.theme.colors.selectedTheme.text.value};
margin: 20px 0;
Expand Down
66 changes: 42 additions & 24 deletions sections/dashboard/FuturesPositionsTable/MobilePositionRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type MobilePositionRowProps = {
const MobilePositionRow: React.FC<MobilePositionRowProps> = ({ row, onClick }) => {
return (
<OpenPositionContainer side={row.position} key={row.asset} onClick={onClick}>
<div style={{ display: 'flex' }}>
<CurrencyDetailsContainer>
<StyledCurrencyIcon currencyKey={row.marketKey} />
<div>
<OpenPositionSize>
Expand All @@ -31,46 +31,52 @@ const MobilePositionRow: React.FC<MobilePositionRowProps> = ({ row, onClick }) =
<span className="leverage">{formatNumber(row.leverage ?? 0, { maxDecimals: 1 })}x</span>
</OpenPositionSide>
</div>
</div>
<div>
</CurrencyDetailsContainer>
<RightColumnsContainer>
<div>
<Currency.Price
currencyKey={Synths.sUSD}
price={row.price ?? 0}
sign="$"
formatOptions={isEurForex(row.asset) ? { minDecimals: DEFAULT_FIAT_EURO_DECIMALS } : {}}
/>
<div>
<Currency.Price
currencyKey={Synths.sUSD}
price={row.price ?? 0}
sign="$"
formatOptions={
isEurForex(row.asset) ? { minDecimals: DEFAULT_FIAT_EURO_DECIMALS } : {}
}
/>
</div>
<EntryPrice>
<Currency.Price
currencyKey={Synths.sUSD}
price={row.avgEntryPrice ?? 0}
sign="$"
formatOptions={
isEurForex(row.asset) ? { minDecimals: DEFAULT_FIAT_EURO_DECIMALS } : {}
}
/>
</EntryPrice>
</div>
<EntryPrice>
<Currency.Price
currencyKey={Synths.sUSD}
price={row.avgEntryPrice ?? 0}
sign="$"
formatOptions={isEurForex(row.asset) ? { minDecimals: DEFAULT_FIAT_EURO_DECIMALS } : {}}
/>
</EntryPrice>
</div>
<div>
<ChangePercent value={row.pnlPct ?? 0} />
<div>
<Currency.Price currencyKey={Synths.sUSD} price={row.pnl ?? 0} sign="$" />
<ChangePercent value={row.pnlPct ?? 0} />
<div>
<Currency.Price currencyKey={Synths.sUSD} price={row.pnl ?? 0} sign="$" />
</div>
</div>
</div>
</RightColumnsContainer>
</OpenPositionContainer>
);
};

const OpenPositionContainer = styled.div<{ side?: PositionSide }>`
background: ${(props) => props.theme.colors.selectedTheme.button.background};
display: flex;
justify-content: space-between;
margin: 15px 0;
margin-bottom: 15px;
padding: 10px;
border-radius: 8px;
box-sizing: border-box;
position: relative;

${border};
background: ${(props) => props.theme.colors.selectedTheme.button.fill};

${(props) =>
props.side === PositionSide.LONG &&
Expand Down Expand Up @@ -147,4 +153,16 @@ const StyledCurrencyIcon = styled(Currency.Icon)`
margin-right: 8px;
`;

const CurrencyDetailsContainer = styled.div`
display: flex;
width: 125px;
margin-right: 30px;
`;

const RightColumnsContainer = styled.div`
display: flex;
flex: 1;
justify-content: space-between;
`;

export default MobilePositionRow;
6 changes: 3 additions & 3 deletions sections/dashboard/MobileDashboard/FuturesMarkets.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const FuturesMarkets = () => {
<MarketStat>
<div className="title">24h Volume</div>
<div className="value">
{formatCurrency(Synths.sUSD, dailyTradeStats.data?.totalVolume || zeroBN, {
{formatCurrency(Synths.sUSD, dailyTradeStats.data?.totalVolume ?? zeroBN, {
sign: '$',
minDecimals: 0,
})}
Expand All @@ -42,14 +42,14 @@ const FuturesMarkets = () => {
<MarketStat>
<div className="title">Open Interest</div>
<div className="value">
{formatCurrency(Synths.sUSD, openInterest ?? 0, {
{formatCurrency(Synths.sUSD, openInterest, {
sign: '$',
minDecimals: 0,
})}
</div>
</MarketStat>
<MarketStat>
<div className="title">Total Trades</div>
<div className="title">24H Trades</div>
<div className="value">
{formatNumber(dailyTradeStats.data?.totalTrades ?? 0, { minDecimals: 0 })}
</div>
Expand Down
Loading