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.5.3 #2765

Merged
merged 5 commits into from
Aug 19, 2023
Merged

v7.5.3 #2765

Show file tree
Hide file tree
Changes from all commits
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "kwenta",
"version": "7.5.2",
"version": "7.5.3",
"description": "Kwenta",
"main": "index.js",
"scripts": {
Expand Down
3 changes: 2 additions & 1 deletion packages/app/.env.local.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ NEXT_PUBLIC_COMPETITION_ACTIVE=false
NEXT_PUBLIC_CLOSE_ONLY=false
NEXT_PUBLIC_WALLETCONNECT_V2_ID="WALLETCONNECT_V2_ID"
NEXT_PUBLIC_DEVNET_ENABLED=true
NEXT_PUBLIC_DEVNET_RPC_URL="NEXT_PUBLIC_DEVNET_RPC_URL"
NEXT_PUBLIC_DEVNET_RPC_URL="NEXT_PUBLIC_DEVNET_RPC_URL"
NEXT_PUBLIC_ONE_INCH_COINGECKO_PROXY="http://[HOST]:[PORT]" # http://localhost:5001
2 changes: 1 addition & 1 deletion packages/app/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kwenta/app",
"version": "7.5.2",
"version": "7.5.3",
"scripts": {
"dev": "next",
"build": "next build",
Expand Down
133 changes: 4 additions & 129 deletions packages/app/src/__tests__/pages/smartMargin.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -223,46 +223,7 @@ describe('Futures market page - stop loss validation', () => {
sdk.futures = mockFuturesService()
})

test('Restricts stop loss for LONG trade at correct price depending on leverage', async () => {
const store = setupStore(preloadedStateWithSmartMarginAccount())
const { findByTestId, findByText } = render(
<MockProviders route="market/?accountType=smart_margin&asset=sETH" store={store}>
<Market />
</MockProviders>
)

const marginInput = await findByTestId('set-order-margin-susd-desktop')
fireEvent.change(marginInput, { target: { value: '100' } })

const sizeInput = await findByTestId('set-order-size-amount-susd-desktop')
fireEvent.change(sizeInput, { target: { value: '1000' } })

const fees = await findByText('$1.69')
expect(fees).toBeTruthy()

const submitButton = await findByTestId('trade-panel-submit-button')
expect(submitButton).toBeEnabled()

const expandButton = await findByTestId('expand-sl-tp-button')
fireEvent.click(expandButton)

const approveButton = await findByTestId('sl-tp-ack-proceed')
fireEvent.click(approveButton)

const stopLossInput = await findByTestId('trade-panel-stop-loss-input')
fireEvent.change(stopLossInput, { target: { value: '1700' } })

// Min / Max SL is shown when invalid
const slMinMaxLabel = await findByText('Min: 1,735.52')
expect(slMinMaxLabel).toBeTruthy()
expect(submitButton).toBeDisabled()

// Input valid when above min
fireEvent.change(stopLossInput, { target: { value: '1750' } })
expect(submitButton).toBeEnabled()
})

test('Restricts stop loss for SHORT trade at correct price depending on leverage', async () => {
test('Displays stop-loss warning in confirmation view when within 5% of liquidation price', async () => {
const store = setupStore(preloadedStateWithSmartMarginAccount())
const { findByTestId, findByText } = render(
<MockProviders route="market/?accountType=smart_margin&asset=sETH" store={store}>
Expand All @@ -275,7 +236,7 @@ describe('Futures market page - stop loss validation', () => {
...MOCK_TRADE_PREVIEW,
liqPrice: wei('2172.467580351348039045'),
side: PositionSide.SHORT,
size: wei('-0.541100000000000000'),
size: wei('-0.5411'),
})

const shortToggle = await findByTestId('position-side-short-button')
Expand All @@ -290,105 +251,19 @@ describe('Futures market page - stop loss validation', () => {
const fees = await findByText('$1.69')
expect(fees).toBeTruthy()

const submitButton = await findByTestId('trade-panel-submit-button')
expect(submitButton).toBeEnabled()

const expandButton = await findByTestId('expand-sl-tp-button')
fireEvent.click(expandButton)

const approveButton = await findByTestId('sl-tp-ack-proceed')
fireEvent.click(approveButton)

const stopLossInput = await findByTestId('trade-panel-stop-loss-input')
fireEvent.change(stopLossInput, { target: { value: '2160' } })
fireEvent.change(stopLossInput, { target: { value: '1700' } })

// Min / Max SL is shown when invalid
// Liqudation price is 2,172.46 and stop is limited to 2,172.29
const slMinMaxLabel = await findByText('Max: 2,107.29')
const slMinMaxLabel = await findByText('Max: 2,172.47')
expect(slMinMaxLabel).toBeTruthy()

expect(submitButton).toBeDisabled()

// Input valid when below max
fireEvent.change(stopLossInput, { target: { value: '2099' } })
expect(submitButton).toBeEnabled()
})

test('Stop loss becomes disabled above a certain leverage', async () => {
const store = setupStore(preloadedStateWithSmartMarginAccount())
const { findByTestId, findByText } = render(
<MockProviders route="market/?accountType=smart_margin&asset=sETH" store={store}>
<Market />
</MockProviders>
)

sdk.futures.getSmartMarginTradePreview = () =>
Promise.resolve({
...MOCK_TRADE_PREVIEW,
liqPrice: wei('1795'),
size: wei('1.1'),
leverage: wei('40'),
})

const marginInput = await findByTestId('set-order-margin-susd-desktop')
fireEvent.change(marginInput, { target: { value: '100' } })

const sizeInput = await findByTestId('set-order-size-amount-susd-desktop')
fireEvent.change(sizeInput, { target: { value: '4000' } })

const fees = await findByText('$1.69')
expect(fees).toBeTruthy()

const submitButton = await findByTestId('trade-panel-submit-button')
expect(submitButton).toBeEnabled()

const expandButton = await findByTestId('expand-sl-tp-button')
fireEvent.click(expandButton)

const approveButton = await findByTestId('sl-tp-ack-proceed')
fireEvent.click(approveButton)

const stopLossInput = await findByTestId('trade-panel-stop-loss-input')

await findByText('Leverage Too High')
expect(stopLossInput).toBeDisabled()
})

test('Displays stop-loss warning in confirmation view when within 5% of liquidation price', async () => {
const store = setupStore(preloadedStateWithSmartMarginAccount())
const { findByTestId, findByText } = render(
<MockProviders route="market/?accountType=smart_margin&asset=sETH" store={store}>
<Market />
</MockProviders>
)

sdk.futures.getSmartMarginTradePreview = () =>
Promise.resolve({
...MOCK_TRADE_PREVIEW,
liqPrice: wei('2172.467580351348039045'),
side: PositionSide.SHORT,
size: wei('-0.5411'),
})

const shortToggle = await findByTestId('position-side-short-button')
fireEvent.click(shortToggle)

const marginInput = await findByTestId('set-order-margin-susd-desktop')
fireEvent.change(marginInput, { target: { value: '100' } })

const sizeInput = await findByTestId('set-order-size-amount-susd-desktop')
fireEvent.change(sizeInput, { target: { value: '1000' } })

const fees = await findByText('$1.69')
expect(fees).toBeTruthy()

const expandButton = await findByTestId('expand-sl-tp-button')
fireEvent.click(expandButton)

const approveButton = await findByTestId('sl-tp-ack-proceed')
fireEvent.click(approveButton)

const stopLossInput = await findByTestId('trade-panel-stop-loss-input')
fireEvent.change(stopLossInput, { target: { value: '2090' } })

const submitButton = await findByTestId('trade-panel-submit-button')
Expand Down
5 changes: 3 additions & 2 deletions packages/app/src/queries/futures/useGetFuturesTrades.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,11 @@ const useGetFuturesTrades = (
getNextPageParam: (lastPage) => {
return notNill(lastPage) && lastPage?.length > 0
? {
minTs: 0,
maxTs: lastPage[lastPage.length - 1].timestamp,
}
: null
: {
maxTs: 0,
}
},
getPreviousPageParam: (firstPage) => {
return notNill(firstPage) && firstPage?.length > 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,6 @@ export default function EditStopLossAndTakeProfitModal() {

const onSelectStopLossPercent = useCallback(
(index: number) => {
if (slValidity.disabled) return
const option = SL_OPTIONS[index]
if (option === 'none') {
dispatch(setSLTPModalStopLoss(''))
Expand All @@ -162,7 +161,7 @@ export default function EditStopLossAndTakeProfitModal() {
dispatch(setSLTPModalStopLoss(stopLoss.toString(dp)))
}
},
[marketPrice, dispatch, position?.activePosition.side, leverageWei, slValidity.disabled]
[marketPrice, dispatch, position?.activePosition.side, leverageWei]
)

const onSelectTakeProfit = useCallback(
Expand Down Expand Up @@ -246,8 +245,6 @@ export default function EditStopLossAndTakeProfitModal() {

<EditStopLossAndTakeProfitInput
type={'stop-loss'}
disabled={!!slValidity.disabled}
disabledReason={slValidity.disabled ? 'Leverage Too High' : undefined}
positionSide={position?.activePosition.side || PositionSide.LONG}
leverage={position?.activePosition.leverage || wei(1)}
invalid={slValidity.invalid}
Expand All @@ -258,7 +255,6 @@ export default function EditStopLossAndTakeProfitModal() {
/>

<SelectorButtons
disabled={slValidity.disabled}
onSelect={onSelectStopLossPercent}
options={SL_OPTIONS}
type={'pill-button-large'}
Expand Down
5 changes: 1 addition & 4 deletions packages/app/src/sections/futures/Trade/SLTPInputs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ export default function SLTPInputs() {

const onSelectStopLossPercent = useCallback(
(index: number) => {
if (slValidity.disabled) return
const option = SL_OPTIONS[index]
const percent = Math.abs(Number(option.replace('%', ''))) / 100
const relativePercent = wei(percent).div(leverageWei)
Expand All @@ -69,7 +68,7 @@ export default function SLTPInputs() {
const dp = suggestedDecimals(stopLoss)
dispatch(setSmartMarginTradeStopLoss(stopLoss.toString(dp)))
},
[currentPrice, dispatch, leverageSide, leverageWei, slValidity.disabled]
[currentPrice, dispatch, leverageSide, leverageWei]
)

const onSelectTakeProfit = useCallback(
Expand Down Expand Up @@ -141,8 +140,6 @@ export default function SLTPInputs() {
/>

<SLTPInputField
disabled={!!slValidity.disabled}
disabledReason={slValidity.disabled ? 'Leverage Too High' : undefined}
invalid={slValidity.invalid}
value={stopLossPrice}
type={'stop-loss'}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export const SelectCurrencyModal: FC<SelectCurrencyModalProps> = ({
const [page, setPage] = useState(1)

// Disable 1inch for now
const oneInchEnabled = false
const oneInchEnabled = network === 10

const allSynths = useMemo(() => getSynthsListForNetwork(network as NetworkId), [network])

Expand Down
5 changes: 3 additions & 2 deletions packages/app/src/state/futures/smartMargin/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ import {
selectSmartMarginDelayedOrders,
selectV2SkewAdjustedPrice,
selectRequiredEthForPendingOrders,
selectAllSmartMarginPositions,
} from './selectors'
import { SmartMarginBalanceInfo } from './types'

Expand Down Expand Up @@ -351,7 +352,7 @@ export const fetchSmartMarginTradePreview = createAsyncThunk<
async (params, { dispatch, getState, extra: { sdk } }) => {
const account = selectSmartMarginAccount(getState())
const freeMargin = selectTotalAvailableMargin(getState())
const positions = selectSmartMarginActivePositions(getState())
const positions = selectAllSmartMarginPositions(getState())
const position = positions.find((p) => p.market.marketKey === params.market.key)

const marketMargin = position?.remainingMargin ?? wei(0)
Expand All @@ -367,7 +368,7 @@ export const fetchSmartMarginTradePreview = createAsyncThunk<
// If this is a trade with no existsing position size then we need to subtract
// remaining idle market margin to get an accurate preview
const marginDelta =
(!position || position.activePosition.size.abs().eq(0)) &&
(!position?.activePosition || position.activePosition?.size.abs().eq(0)) &&
marketMargin.gt(0) &&
params.action === 'trade'
? params.marginDelta.sub(marketMargin)
Expand Down
4 changes: 2 additions & 2 deletions packages/app/src/utils/__tests__/futures.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ describe('futures utils', () => {
test('correct stop loss limitation when LONG', () => {
// Traders can place stop losses at 1% above liquidation price
const minStopLoss = minMaxSLPrice(wei(1800), PositionSide.LONG)
expect(minStopLoss?.toNumber()).toEqual(1854)
expect(minStopLoss?.toNumber()).toEqual(1800)
})

test('correct stop loss limitation when SHORT', () => {
// Traders can place stop losses at 1% below liquidation price
const minStopLoss = minMaxSLPrice(wei(2200), PositionSide.SHORT)
expect(minStopLoss?.toNumber()).toEqual(2134)
expect(minStopLoss?.toNumber()).toEqual(2200)
})
})
12 changes: 3 additions & 9 deletions packages/app/src/utils/futures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -518,8 +518,8 @@
notionalValue: wei(preview.notionalValue),
priceImpact: wei(preview.priceImpact),
})
// Disable stop loss when it is within 3% of the liquidation price
const SL_LIQ_DISABLED_PERCENT = 0.03
// Disable stop loss when it is within 0% of the liquidation price
const SL_LIQ_DISABLED_PERCENT = 0

// Warn users when their stop loss is within 7.5% of their liquidation price
const SL_LIQ_PERCENT_WARN = 0.075
Expand All @@ -538,19 +538,14 @@
) => {
const minMaxStopPrice = minMaxSLPrice(liqPrice, side)

const disabled =
(side === PositionSide.LONG && minMaxStopPrice?.gt(currentPrice || 0)) ||
(side === PositionSide.SHORT && minMaxStopPrice?.lt(currentPrice || 0))

if (stopLossPrice === '' || stopLossPrice === undefined)
return {
invalid: false,
disabled: disabled,
minMaxStopPrice,
}

if (!minMaxStopPrice || !liqPrice || liqPrice.eq(0))
return { invalid: false, disabled, minMaxStopPrice, invalidReason: 'no_liquidation_price' }
return { invalid: false, minMaxStopPrice, invalidReason: 'no_liquidation_price' }

Check warning on line 548 in packages/app/src/utils/futures.ts

View check run for this annotation

Codecov / codecov/patch

packages/app/src/utils/futures.ts#L548

Added line #L548 was not covered by tests

let invalid = false
if (side === 'long') {
Expand All @@ -569,7 +564,6 @@
return {
invalid,
minMaxStopPrice,
disabled,
invalidReason: invalid ? 'exceeds_max_stop' : undefined,
showWarning: percent.lt(SL_LIQ_PERCENT_WARN),
}
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kwenta/sdk",
"version": "1.0.7",
"version": "1.0.8",
"description": "SDK for headless interaction with Kwenta",
"main": "dist/index.js",
"directories": {
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/src/constants/exchange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import keyBy from 'lodash/keyBy'

import { FuturesMarketKey } from '../types/futures'

export const CG_BASE_API_URL = 'https://api.coingecko.com/api/v3'
export const CG_BASE_API_URL = `${process.env.NEXT_PUBLIC_ONE_INCH_COINGECKO_PROXY}/coingecko/api/v3`

export const PROTOCOLS =
'OPTIMISM_UNISWAP_V3,OPTIMISM_SYNTHETIX,OPTIMISM_SYNTHETIX_WRAPPER,OPTIMISM_ONE_INCH_LIMIT_ORDER,OPTIMISM_ONE_INCH_LIMIT_ORDER_V2,OPTIMISM_CURVE,OPTIMISM_BALANCER_V2,OPTIMISM_VELODROME,OPTIMISM_KYBERSWAP_ELASTIC'
Expand Down
Loading
Loading