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

v7.9.3 #2792

Merged
merged 2 commits into from
Sep 24, 2023
Merged

v7.9.3 #2792

Show file tree
Hide file tree
Changes from 1 commit
Commits
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
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { MIN_MARGIN_AMOUNT, ZERO_WEI } from '@kwenta/sdk/constants'
import { PositionSide, SwapDepositToken } from '@kwenta/sdk/types'
import { PositionSide } from '@kwenta/sdk/types'
import {
OrderNameByType,
formatCurrency,
Expand All @@ -9,7 +9,7 @@ import {
stripZeros,
} from '@kwenta/sdk/utils'
import Wei, { wei } from '@synthetixio/wei'
import { FC, useCallback, useMemo, useReducer, useState } from 'react'
import { FC, useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'

Expand All @@ -18,25 +18,19 @@ import BaseModal from 'components/BaseModal'
import Button from 'components/Button'
import ErrorView from 'components/ErrorView'
import { FlexDivRowCentered } from 'components/layout/flex'
import { ButtonLoader, MiniLoader } from 'components/Loader'
import { ButtonLoader } from 'components/Loader'
import { StyledCaretDownIcon } from 'components/Select'
import Spacer from 'components/Spacer'
import Tooltip from 'components/Tooltip/Tooltip'
import { NO_VALUE } from 'constants/placeholder'
import { SWAP_DEPOSIT_TRADE_ENABLED } from 'constants/ui'
import { selectMarketAsset } from 'state/futures/common/selectors'
import {
selectLeverageSide,
selectPosition,
selectLeverageInput,
selectTradePanelSLTPValidity,
} from 'state/futures/selectors'
import {
calculateTradeSwapDeposit,
refetchTradePreview,
submitSmartMarginOrder,
} from 'state/futures/smartMargin/actions'
import { clearTradeSwapDepositQuote } from 'state/futures/smartMargin/reducer'
import { refetchTradePreview, submitSmartMarginOrder } from 'state/futures/smartMargin/actions'
import {
selectKeeperDepositExceedsBal,
selectNewTradeHasSlTp,
Expand All @@ -45,13 +39,8 @@ import {
selectSelectedSwapDepositToken,
selectSmartMarginOrderPrice,
selectTradePreview,
selectSmartMarginQueryStatuses,
selectTradeSwapDepositQuote,
selectSwapDepositQuoteLoading,
selectQuoteInvalidReason,
} from 'state/futures/smartMargin/selectors'
import { useAppDispatch, useAppSelector, useFetchAction, usePollAction } from 'state/hooks'
import { FetchStatus } from 'state/types'
import { useAppDispatch, useAppSelector, usePollAction } from 'state/hooks'

import AcceptWarningView from '../../../components/AcceptWarningView'

Expand Down Expand Up @@ -91,9 +80,6 @@ export default function TradeConfirmationModal({
const ethBalanceExceeded = useAppSelector(selectKeeperDepositExceedsBal)
const hasSlTp = useAppSelector(selectNewTradeHasSlTp)
const sltpValidity = useAppSelector(selectTradePanelSLTPValidity)
const quoteInvalidReason = useAppSelector(selectQuoteInvalidReason)
const quote = useAppSelector(selectTradeSwapDepositQuote)
const quoteLoading = useAppSelector(selectSwapDepositQuoteLoading)
const swapToken = useAppSelector(selectSelectedSwapDepositToken)

const [overridePriceProtection, setOverridePriceProtection] = useState(false)
Expand All @@ -103,10 +89,6 @@ export default function TradeConfirmationModal({

const onConfirmOrder = useCallback(() => dispatch(submitSmartMarginOrder(true)), [dispatch])

useFetchAction(calculateTradeSwapDeposit, {
dependencies: [potentialTradeDetails?.margin.toString()],
})

const positionSide = useMemo(() => {
if (potentialTradeDetails?.size.eq(ZERO_WEI)) {
return position?.activePosition?.side === PositionSide.LONG
Expand Down Expand Up @@ -139,19 +121,7 @@ export default function TradeConfirmationModal({
? t('futures.market.trade.confirmation.modal.eth-bal-warning')
: null

const quoteInvalidError = useMemo(() => {
return !!quoteInvalidReason
? t(`futures.market.trade.confirmation.modal.quote-invalid-error-${quoteInvalidReason}`)
: null
}, [quoteInvalidReason, t])

const disabledReason = useMemo(() => {
if (!!quoteInvalidReason) {
return t('futures.market.trade.confirmation.modal.disabled-quote-invalid')
}
if (!quote && quoteLoading) {
return t('futures.market.trade.confirmation.modal.disabled-quote-loading')
}
if (showEthBalWarning) {
return t('futures.market.trade.confirmation.modal.disabled-eth-bal', {
depositAmount: formatNumber(stripZeros(keeperFee?.toString()), { suggestDecimals: true }),
Expand All @@ -169,15 +139,11 @@ export default function TradeConfirmationModal({
keeperFee,
overridePriceProtection,
positionDetails?.exceedsPriceProtection,
quoteInvalidReason,
quote,
quoteLoading,
])

const handleDismiss = useCallback(() => {
dispatch(clearTradeSwapDepositQuote())
onDismiss()
}, [dispatch, onDismiss])
}, [onDismiss])

const buttonText = allowanceValid
? t(`futures.market.trade.confirmation.modal.confirm-order.${leverageSide}`)
Expand Down Expand Up @@ -211,7 +177,6 @@ export default function TradeConfirmationModal({
<TotalFeeRow executionFee={executionFee} />
<KeeperFeeRow keeperFee={keeperFee} />
<GasFeeRow gasFee={gasFee} />
{SWAP_DEPOSIT_TRADE_ENABLED && <SwapRow />}
</RowsContainer>
{positionDetails?.exceedsPriceProtection && (
<AcceptWarningView
Expand Down Expand Up @@ -248,7 +213,7 @@ export default function TradeConfirmationModal({
{(errorMessage || ethBalWarningMessage) && (
<ErrorView
messageType={ethBalWarningMessage ? 'warn' : 'error'}
message={errorMessage ?? ethBalWarningMessage ?? quoteInvalidError}
message={errorMessage ?? ethBalWarningMessage}
containerStyle={{ margin: '16px 0 0 0' }}
/>
)}
Expand Down Expand Up @@ -447,53 +412,6 @@ const GasFeeRow: FC<GasFeeRowProps> = ({ gasFee }) => {
return null
}

const SwapRow = () => {
const swapDepositToken = useAppSelector(selectSelectedSwapDepositToken)
const [expanded, toggleExpanded] = useReducer((e) => !e, false)

const { tradeSwapDepositQuote } = useAppSelector(selectSmartMarginQueryStatuses)
const quote = useAppSelector(selectTradeSwapDepositQuote)

if (swapDepositToken === SwapDepositToken.SUSD) return null

return (
<DataRow
expanded={expanded}
onToggleExpand={toggleExpanded}
label="Swap"
value={
tradeSwapDepositQuote.status === FetchStatus.Loading ? (
<MiniLoader />
) : quote ? (
`${formatNumber(quote?.amountIn ?? 0, { suggestDecimals: true })} ${
quote?.token
} -> ${formatNumber(quote?.amountOut ?? 0, { suggestDecimals: true })} sUSD`
) : (
'-'
)
}
>
<ExchangeRateRow />
</DataRow>
)
}

const ExchangeRateRow = () => {
const swapDepositToken = useAppSelector(selectSelectedSwapDepositToken)
const quote = useAppSelector(selectTradeSwapDepositQuote)
const price = useMemo(() => {
if (!quote) return 0
return quote.amountOut.div(quote.amountIn)
}, [quote])

return (
<DataRow
label="Exchange Rate"
value={`1 ${swapDepositToken} = ${formatNumber(price, { suggestDecimals: true })} sUSD`}
/>
)
}

const StyledBaseModal = styled(BaseModal)`
[data-reach-dialog-content] {
width: 400px;
Expand Down
1 change: 0 additions & 1 deletion packages/app/src/state/futures/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ export type SmartMarginQueryStatuses = FuturesQueryStatuses & {
smartMarginBalanceInfo: QueryStatus
swapDepositBalanceQuote: QueryStatus
swapDepositQuote: QueryStatus
tradeSwapDepositQuote: QueryStatus
}

export type TradeSizeInputs<T = Wei> = {
Expand Down
76 changes: 2 additions & 74 deletions packages/app/src/state/futures/smartMargin/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import {
import { fetchBalances } from 'state/balances/actions'
import { EST_KEEPER_GAS_FEE, ZERO_CM_FEES, ZERO_STATE_TRADE_INPUTS } from 'state/constants'
import { serializeWeiObject } from 'state/helpers'
import { selectSelectedEpoch } from 'state/staking/selectors'
import { AppDispatch, AppThunk, RootState } from 'state/store'
import { ThunkConfig } from 'state/types'
import { selectNetwork, selectWallet } from 'state/wallet/selectors'
Expand Down Expand Up @@ -98,13 +99,7 @@ import {
clearSmartMarginTradePreviews,
setKeeperDeposit,
} from './reducer'
import {
selectIdleAccountMargin,
selectSelectedSwapDepositToken,
selectSwapDepositBalance,
selectSwapDepositBalanceQuote,
selectTradeSwapDepositQuote,
} from './selectors'
import { selectSelectedSwapDepositToken, selectSwapDepositBalance } from './selectors'
import {
selectSmartMarginAccount,
selectSmartMarginMarginDelta,
Expand Down Expand Up @@ -137,7 +132,6 @@ import {
selectAllSmartMarginPositions,
} from './selectors'
import { SmartMarginBalanceInfo } from './types'
import { selectSelectedEpoch } from 'state/staking/selectors'

export const fetchMarketsV2 = createAsyncThunk<
{ markets: PerpsMarketV2<string>[]; networkId: NetworkId } | undefined,
Expand Down Expand Up @@ -429,64 +423,6 @@ export const fetchSmartMarginTradePreview = createAsyncThunk<
}
)

export const calculateTradeSwapDeposit = createAsyncThunk<
| {
token: SwapDepositToken
amountIn: string
amountOut: string
quoteInvalidReason?: `insufficient-${'balance' | 'quote'}`
}
| undefined,
void,
ThunkConfig
>('futures/calculateTradeSwapDeposit', async (_, { getState }) => {
const state = getState()
const wallet = selectWallet(state)
const marketInfo = selectV2MarketInfo(state)
const swapDepositToken = selectSelectedSwapDepositToken(state)
const marginDelta = selectSmartMarginMarginDelta(state)
const idleMargin = selectIdleAccountMargin(state)
const swapDepositBalance = selectSwapDepositBalance(state)
const balanceQuote = selectSwapDepositBalanceQuote(state)

if (!wallet || !marketInfo || !swapDepositToken || swapDepositToken === SwapDepositToken.SUSD)
return

try {
const requiredSwapDeposit = marginDelta.sub(idleMargin)

if (requiredSwapDeposit.lte(0)) {
return
}

// Add some buffer to account for price change since quote
// but keeping within the bounds of original balance quote

const depositWithBuffer = requiredSwapDeposit.add(
requiredSwapDeposit.mul(SWAP_QUOTE_BUFFER).div(100)
)

const tokenInAmount = depositWithBuffer.div(balanceQuote?.rate || 0)

let quoteInvalidReason: `insufficient-${'balance' | 'quote'}` | undefined = undefined

if (tokenInAmount.gt(swapDepositBalance)) {
quoteInvalidReason = 'insufficient-balance'
}

return {
token: swapDepositToken,
amountIn: tokenInAmount.toString(),
amountOut: requiredSwapDeposit.toString(),
quoteInvalidReason,
}
} catch (err) {
logError(err)
notifyError('Failed to calculate swap deposit', err)
throw err
}
})

export const clearTradeInputs = createAsyncThunk<void, void, ThunkConfig>(
'futures/clearTradeInputs',
async (_, { dispatch }) => {
Expand Down Expand Up @@ -1079,7 +1015,6 @@ export const submitSmartMarginOrder = createAsyncThunk<void, boolean, ThunkConfi
const position = selectSelectedSmartMarginPosition(state)
const openDelayedOrders = selectSmartMarginDelayedOrders(state)
const { stopLossPrice, takeProfitPrice } = selectSlTpTradeInputs(state)
const swapQuote = selectTradeSwapDepositQuote(state)

try {
if (!marketInfo) throw new Error('Market info not found')
Expand Down Expand Up @@ -1166,13 +1101,6 @@ export const submitSmartMarginOrder = createAsyncThunk<void, boolean, ThunkConfi
options: {
cancelPendingReduceOrders: isClosing,
cancelExpiredDelayedOrders: !!staleOrder,
swapDeposit: swapQuote
? {
...swapQuote,
amountOutMin: swapQuote.amountOut,
amountIn: swapQuote.amountIn,
}
: undefined,
},
})
await monitorAndAwaitTransaction(dispatch, tx)
Expand Down
20 changes: 0 additions & 20 deletions packages/app/src/state/futures/smartMargin/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ import {
fetchFuturesFees,
fetchFuturesFeesForAccount,
fetchSwapDepositBalanceQuote,
calculateTradeSwapDeposit,
} from './actions'
import {
SmartMarginAccountData,
Expand Down Expand Up @@ -73,7 +72,6 @@ export const SMART_MARGIN_INITIAL_STATE: SmartMarginState = {
futuresFeesForAccount: DEFAULT_QUERY_STATUS,
swapDepositBalanceQuote: DEFAULT_QUERY_STATUS,
swapDepositQuote: DEFAULT_QUERY_STATUS,
tradeSwapDepositQuote: DEFAULT_QUERY_STATUS,
},
accounts: DEFAULT_MAP_BY_NETWORK,
selectedMarketAsset: FuturesMarketAsset.sETH,
Expand Down Expand Up @@ -265,9 +263,6 @@ const smartMarginSlice = createSlice({
setSwapDepositCustomSlippage: (smartMargin, action) => {
smartMargin.swapDepositCustomSlippage = action.payload
},
clearTradeSwapDepositQuote: (smartMargin) => {
smartMargin.tradeSwapDepositQuote = undefined
},
},
extraReducers: (builder) => {
// Markets
Expand Down Expand Up @@ -549,20 +544,6 @@ const smartMarginSlice = createSlice({
error: 'Failed to fetch quote for the swap deposit token',
}
})

builder.addCase(calculateTradeSwapDeposit.pending, (futuresState) => {
futuresState.queryStatuses.tradeSwapDepositQuote = LOADING_STATUS
})
builder.addCase(calculateTradeSwapDeposit.fulfilled, (futuresState, action) => {
futuresState.queryStatuses.tradeSwapDepositQuote = SUCCESS_STATUS
futuresState.tradeSwapDepositQuote = action.payload
})
builder.addCase(calculateTradeSwapDeposit.rejected, (futuresState) => {
futuresState.queryStatuses.tradeSwapDepositQuote = {
status: FetchStatus.Error,
error: 'Failed to fetch quote for the swap deposit',
}
})
},
})

Expand Down Expand Up @@ -596,7 +577,6 @@ export const {
setSLTPModalTakeProfit,
setSwapDepositSlippage,
setSwapDepositCustomSlippage,
clearTradeSwapDepositQuote,
} = smartMarginSlice.actions

const findWalletForAccount = (
Expand Down
Loading
Loading