Merge pull request #174 from blockworks-foundation/stop-orders

stop orders
This commit is contained in:
saml33 2023-08-18 08:08:21 +10:00 committed by GitHub
commit 402437bbf6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 2454 additions and 655 deletions

View File

@ -1,3 +1,5 @@
import { Bank } from '@blockworks-foundation/mango-v4'
type CoingeckoOhlcv = [
time: number,
open: number,
@ -15,17 +17,22 @@ export type ChartDataItem = {
export const fetchChartData = async (
baseTokenId: string | undefined,
inputBank: Bank | undefined,
quoteTokenId: string | undefined,
outputBank: Bank | undefined,
daysToShow: string,
flipPrices: boolean,
): Promise<ChartDataItem[]> => {
if (!baseTokenId || !quoteTokenId) return []
const baseId = flipPrices ? baseTokenId : quoteTokenId
const quoteId = flipPrices ? quoteTokenId : baseTokenId
try {
const [inputResponse, outputResponse] = await Promise.all([
fetch(
`https://api.coingecko.com/api/v3/coins/${baseTokenId}/ohlc?vs_currency=usd&days=${daysToShow}`,
`https://api.coingecko.com/api/v3/coins/${baseId}/ohlc?vs_currency=usd&days=${daysToShow}`,
),
fetch(
`https://api.coingecko.com/api/v3/coins/${quoteTokenId}/ohlc?vs_currency=usd&days=${daysToShow}`,
`https://api.coingecko.com/api/v3/coins/${quoteId}/ohlc?vs_currency=usd&days=${daysToShow}`,
),
])
@ -39,24 +46,28 @@ export const fetchChartData = async (
(outputTokenCandle) => outputTokenCandle[0] === inputTokenCandle[0],
)
if (outputTokenCandle) {
if (['usd-coin', 'tether'].includes(quoteTokenId)) {
parsedData.push({
time: inputTokenCandle[0],
price: inputTokenCandle[4] / outputTokenCandle[4],
inputTokenPrice: inputTokenCandle[4],
outputTokenPrice: outputTokenCandle[4],
})
} else {
parsedData.push({
time: inputTokenCandle[0],
price: outputTokenCandle[4] / inputTokenCandle[4],
inputTokenPrice: inputTokenCandle[4],
outputTokenPrice: outputTokenCandle[4],
})
}
parsedData.push({
time: inputTokenCandle[0],
price: outputTokenCandle[4] / inputTokenCandle[4],
inputTokenPrice: inputTokenCandle[4],
outputTokenPrice: outputTokenCandle[4],
})
}
}
return parsedData
if (inputBank && outputBank) {
const latestPrice = flipPrices
? outputBank.uiPrice / inputBank.uiPrice
: inputBank.uiPrice / outputBank.uiPrice
const item: ChartDataItem[] = [
{
price: latestPrice,
time: Date.now(),
inputTokenPrice: inputBank.uiPrice,
outputTokenPrice: outputBank.uiPrice,
},
]
return parsedData.concat(item)
} else return parsedData
} else {
return []
}

View File

@ -26,7 +26,7 @@ import Button from './shared/Button'
import InlineNotification from './shared/InlineNotification'
import Loading from './shared/Loading'
import { EnterBottomExitBottom, FadeInFadeOut } from './shared/Transitions'
import { withValueLimit } from './swap/SwapForm'
import { withValueLimit } from './swap/MarketSwapForm'
import { getMaxWithdrawForBank } from './swap/useTokenMax'
import MaxAmountButton from '@components/shared/MaxAmountButton'
import HealthImpactTokenChange from '@components/HealthImpactTokenChange'

View File

@ -21,7 +21,7 @@ import Label from './forms/Label'
import Button, { IconButton } from './shared/Button'
import Loading from './shared/Loading'
import { EnterBottomExitBottom, FadeInFadeOut } from './shared/Transitions'
import { withValueLimit } from './swap/SwapForm'
import { withValueLimit } from './swap/MarketSwapForm'
import MaxAmountButton from '@components/shared/MaxAmountButton'
import Tooltip from '@components/shared/Tooltip'
import HealthImpactTokenChange from '@components/HealthImpactTokenChange'

View File

@ -16,7 +16,7 @@ import Label from './forms/Label'
import Button from './shared/Button'
import Loading from './shared/Loading'
import { EnterBottomExitBottom, FadeInFadeOut } from './shared/Transitions'
import { withValueLimit } from './swap/SwapForm'
import { withValueLimit } from './swap/MarketSwapForm'
import MaxAmountButton from '@components/shared/MaxAmountButton'
import HealthImpactTokenChange from '@components/HealthImpactTokenChange'
import { walletBalanceForToken } from './DepositForm'

View File

@ -46,7 +46,7 @@ const StatusBar = ({ collapsed }: { collapsed: boolean }) => {
<div
className={`hidden fixed ${
collapsed ? 'w-[calc(100vw-64px)]' : 'w-[calc(100vw-200px)]'
} bottom-0 bg-th-input-bkg md:grid md:grid-cols-3 px-4 md:px-6 py-1`}
} bottom-0 bg-th-input-bkg md:grid md:grid-cols-3 px-4 md:px-6 py-1 z-10`}
>
<div className="col-span-1 flex items-center space-x-2">
<Tps />

View File

@ -22,7 +22,7 @@ import Button from './shared/Button'
import InlineNotification from './shared/InlineNotification'
import Loading from './shared/Loading'
import { EnterBottomExitBottom, FadeInFadeOut } from './shared/Transitions'
import { withValueLimit } from './swap/SwapForm'
import { withValueLimit } from './swap/MarketSwapForm'
import { getMaxWithdrawForBank } from './swap/useTokenMax'
import MaxAmountButton from '@components/shared/MaxAmountButton'
import HealthImpactTokenChange from '@components/HealthImpactTokenChange'

View File

@ -12,29 +12,43 @@ import useOpenPerpPositions from 'hooks/useOpenPerpPositions'
import OpenOrders from '@components/trade/OpenOrders'
import HistoryTabs from './HistoryTabs'
import ManualRefresh from '@components/shared/ManualRefresh'
import useMangoAccount from 'hooks/useMangoAccount'
import { useIsWhiteListed } from 'hooks/useIsWhiteListed'
import SwapOrders from '@components/swap/SwapOrders'
const AccountTabs = () => {
const [activeTab, setActiveTab] = useState('balances')
const { mangoAccount } = useMangoAccount()
const { width } = useViewport()
const unsettledSpotBalances = useUnsettledSpotBalances()
const unsettledPerpPositions = useUnsettledPerpPositions()
const openPerpPositions = useOpenPerpPositions()
const openOrders = mangoStore((s) => s.mangoAccount.openOrders)
const isMobile = width ? width < breakpoints.lg : false
const { data: isWhiteListed } = useIsWhiteListed()
const tabsWithCount: [string, number][] = useMemo(() => {
const unsettledTradeCount =
Object.values(unsettledSpotBalances).flat().length +
unsettledPerpPositions?.length
return [
const tabs: [string, number][] = [
['balances', 0],
['trade:positions', openPerpPositions.length],
['trade:orders', Object.values(openOrders).flat().length],
['trade:unsettled', unsettledTradeCount],
['history', 0],
]
if (isWhiteListed) {
const stopOrdersCount =
mangoAccount?.tokenConditionalSwaps.filter((tcs) => tcs.hasData)
?.length || 0
tabs.splice(3, 0, ['trade:trigger-orders', stopOrdersCount])
}
return tabs
}, [
isWhiteListed,
mangoAccount,
openPerpPositions,
unsettledPerpPositions,
unsettledSpotBalances,
@ -72,6 +86,8 @@ const TabContent = ({ activeTab }: { activeTab: string }) => {
return <PerpPositions />
case 'trade:orders':
return <OpenOrders />
case 'trade:trigger-orders':
return <SwapOrders />
case 'trade:unsettled':
return (
<UnsettledTrades

View File

@ -2,35 +2,40 @@
import { Listbox } from '@headlessui/react'
import { ChevronDownIcon } from '@heroicons/react/20/solid'
import { ReactNode } from 'react'
import { TradeForm } from 'types'
interface SelectProps {
value: string | ReactNode
onChange: (x: any) => void
type Values = TradeForm['tradeType'] | ReactNode
interface SelectProps<T extends Values> {
value: T | string
onChange: (x: T) => void
children: ReactNode
className?: string
buttonClassName?: string
dropdownPanelClassName?: string
icon?: ReactNode
placeholder?: string
disabled?: boolean
}
const Select = ({
const Select = <T extends Values>({
value,
onChange,
children,
className,
buttonClassName,
dropdownPanelClassName,
icon,
placeholder = 'Select',
disabled = false,
}: SelectProps) => {
}: SelectProps<T>) => {
return (
<div className={`relative ${className}`}>
<Listbox value={value} onChange={onChange} disabled={disabled}>
{({ open }) => (
<>
<Listbox.Button
className={`h-full w-full rounded-md bg-th-input-bkg py-2.5 font-normal ring-1 ring-inset ring-th-input-border focus:outline-none focus-visible:ring-th-fgd-4 md:hover:ring-th-input-border-hover`}
className={`h-full w-full rounded-md bg-th-input-bkg py-2.5 font-normal ring-1 ring-inset ring-th-input-border focus:outline-none focus-visible:ring-th-fgd-4 md:hover:ring-th-input-border-hover ${buttonClassName}`}
>
<div
className={`flex items-center justify-between space-x-2 px-3 text-th-fgd-1`}

View File

@ -37,7 +37,7 @@ import MaxAmountButton from '../shared/MaxAmountButton'
import SolBalanceWarnings from '../shared/SolBalanceWarnings'
import Modal from '../shared/Modal'
import NumberFormat, { NumberFormatValues } from 'react-number-format'
import { withValueLimit } from '@components/swap/SwapForm'
import { withValueLimit } from '@components/swap/MarketSwapForm'
import useBanksWithBalances from 'hooks/useBanksWithBalances'
import BankAmountWithValue from '@components/shared/BankAmountWithValue'
import { isMangoError } from 'types'

View File

@ -126,8 +126,8 @@ const DisplaySettings = () => {
<p className="mb-2 md:mb-0">{t('settings:theme')}</p>
<div className="w-full min-w-[140px] md:w-auto">
<Select
value={theme}
onChange={(t) => setTheme(t)}
value={theme || DEFAULT_THEMES[0]}
onChange={(t: string) => setTheme(t)}
className="w-full"
>
{themes.map((theme) => (

View File

@ -67,7 +67,14 @@ const TabUnderline = <T extends Values>({
`}
key={`${value}` + i}
>
{names ? names[i] : t(`${value}`)}
<span className="relative">
{names ? names[i] : t(`${value}`)}
{value === 'trade:trigger-order' ? (
<span className="absolute -top-3 -right-5 py-0.5 px-1 rounded bg-th-active font-bold text-xxs leading-none uppercase text-th-bkg-1 ml-2">
beta
</span>
) : null}
</span>
</button>
))}
</nav>

View File

@ -0,0 +1,117 @@
import MaxAmountButton from '@components/shared/MaxAmountButton'
import TokenSelect from './TokenSelect'
import Loading from '@components/shared/Loading'
import NumberFormat, {
NumberFormatValues,
SourceInfo,
} from 'react-number-format'
import { floorToDecimal, formatCurrencyValue } from 'utils/numbers'
import { useTranslation } from 'react-i18next'
import { Dispatch, SetStateAction, useMemo } from 'react'
import mangoStore from '@store/mangoStore'
import useMangoGroup from 'hooks/useMangoGroup'
import { OUTPUT_TOKEN_DEFAULT } from 'utils/constants'
import { NUMBER_FORMAT_CLASSNAMES } from './MarketSwapForm'
import InlineNotification from '@components/shared/InlineNotification'
import useMangoAccount from 'hooks/useMangoAccount'
const BuyTokenInput = ({
error,
handleAmountOutChange,
loading,
setShowTokenSelect,
handleRepay,
}: {
error?: string
handleAmountOutChange: (e: NumberFormatValues, info: SourceInfo) => void
loading?: boolean
setShowTokenSelect: Dispatch<SetStateAction<'input' | 'output' | undefined>>
handleRepay?: (amountOut: string) => void
}) => {
const { t } = useTranslation('common')
const { mangoAccount } = useMangoAccount()
const { group } = useMangoGroup()
const { outputBank, amountOut: amountOutFormValue } = mangoStore(
(s) => s.swap,
)
const outputTokenBalanceBorrow = useMemo(() => {
if (!outputBank || !mangoAccount) return 0
const balance = mangoAccount.getTokenBalanceUi(outputBank)
const roundedBalance = floorToDecimal(
balance,
outputBank.mintDecimals,
).toNumber()
return balance && balance < 0 ? Math.abs(roundedBalance).toString() : 0
}, [mangoAccount, outputBank])
return (
<div className="mb-2 grid grid-cols-2 rounded-xl bg-th-bkg-2 p-3">
<div className="col-span-2 mb-2 flex items-end justify-between">
<p className="text-th-fgd-2">{t('buy')}</p>
{handleRepay && outputTokenBalanceBorrow ? (
<MaxAmountButton
className="mb-0.5 text-xs"
decimals={outputBank?.mintDecimals || 9}
label={t('repay')}
onClick={() => handleRepay(outputTokenBalanceBorrow)}
value={outputTokenBalanceBorrow}
/>
) : null}
</div>
<div className="col-span-1">
<TokenSelect
bank={
outputBank || group?.banksMapByName.get(OUTPUT_TOKEN_DEFAULT)?.[0]
}
showTokenList={setShowTokenSelect}
type="output"
/>
</div>
<div className="relative col-span-1">
{loading ? (
<div className="flex h-[56px] w-full items-center justify-center rounded-l-none rounded-r-lg bg-th-input-bkg">
<Loading />
</div>
) : (
<>
<NumberFormat
inputMode="decimal"
thousandSeparator=","
allowNegative={false}
isNumericString={true}
decimalScale={outputBank?.mintDecimals || 6}
name="amountOut"
id="amountOut"
className={NUMBER_FORMAT_CLASSNAMES}
placeholder="0.00"
value={amountOutFormValue}
onValueChange={handleAmountOutChange}
/>
{!isNaN(Number(amountOutFormValue)) ? (
<span className="absolute right-3 bottom-1.5 text-xxs text-th-fgd-4">
{outputBank
? formatCurrencyValue(
outputBank.uiPrice * Number(amountOutFormValue),
)
: ''}
</span>
) : null}
</>
)}
</div>
{error ? (
<div className="col-span-2 mt-1 flex justify-center">
<InlineNotification
type="error"
desc={error}
hideBorder
hidePadding
/>
</div>
) : null}
</div>
)
}
export default BuyTokenInput

View File

@ -0,0 +1,917 @@
import {
useState,
useCallback,
useEffect,
useMemo,
Dispatch,
SetStateAction,
useLayoutEffect,
} from 'react'
import {
ArrowDownIcon,
ArrowDownTrayIcon,
ArrowsRightLeftIcon,
LinkIcon,
} from '@heroicons/react/20/solid'
import NumberFormat, {
NumberFormatValues,
SourceInfo,
} from 'react-number-format'
import Decimal from 'decimal.js'
import mangoStore from '@store/mangoStore'
import { useTranslation } from 'next-i18next'
import { SIZE_INPUT_UI_KEY } from '../../utils/constants'
import useLocalStorageState from 'hooks/useLocalStorageState'
import SwapSlider from './SwapSlider'
import PercentageSelectButtons from './PercentageSelectButtons'
import { floorToDecimal } from 'utils/numbers'
import { withValueLimit } from './MarketSwapForm'
import SellTokenInput from './SellTokenInput'
import BuyTokenInput from './BuyTokenInput'
import { notify } from 'utils/notifications'
import * as sentry from '@sentry/nextjs'
import { isMangoError } from 'types'
import Button, { LinkButton } from '@components/shared/Button'
import Loading from '@components/shared/Loading'
import TokenLogo from '@components/shared/TokenLogo'
import InlineNotification from '@components/shared/InlineNotification'
import Select from '@components/forms/Select'
import useIpAddress from 'hooks/useIpAddress'
import { Bank, toUiDecimalsForQuote } from '@blockworks-foundation/mango-v4'
import useMangoAccount from 'hooks/useMangoAccount'
import { useWallet } from '@solana/wallet-adapter-react'
import { useTokenMax } from './useTokenMax'
import DepositWithdrawModal from '@components/modals/DepositWithdrawModal'
type LimitSwapFormProps = {
showTokenSelect: 'input' | 'output' | undefined
setShowTokenSelect: Dispatch<SetStateAction<'input' | 'output' | undefined>>
}
type LimitSwapForm = {
amountIn: number
hasBorrows: number | undefined
triggerPrice: string
}
type FormErrors = Partial<Record<keyof LimitSwapForm, string>>
type OrderTypeMultiplier = 0.9 | 1 | 1.1
enum OrderTypes {
STOP_LOSS = 'trade:stop-loss',
TAKE_PROFIT = 'trade:take-profit',
REPAY_BORROW = 'repay-borrow',
}
const ORDER_TYPES = [
OrderTypes.STOP_LOSS,
OrderTypes.TAKE_PROFIT,
OrderTypes.REPAY_BORROW,
]
const set = mangoStore.getState().set
const getSellTokenBalance = (inputBank: Bank | undefined) => {
const mangoAccount = mangoStore.getState().mangoAccount.current
if (!inputBank || !mangoAccount) return 0
const balance = mangoAccount.getTokenBalanceUi(inputBank)
return balance
}
const getOrderTypeMultiplier = (orderType: OrderTypes, flipPrices: boolean) => {
if (orderType === OrderTypes.STOP_LOSS) {
return flipPrices ? 1.1 : 0.9
} else if (orderType === OrderTypes.TAKE_PROFIT) {
return flipPrices ? 0.9 : 1.1
} else {
return 1
}
}
const LimitSwapForm = ({
showTokenSelect,
setShowTokenSelect,
}: LimitSwapFormProps) => {
const { t } = useTranslation(['common', 'swap', 'trade'])
const { mangoAccount, mangoAccountAddress } = useMangoAccount()
const { ipAllowed, ipCountry } = useIpAddress()
const [animateSwitchArrow, setAnimateSwitchArrow] = useState(0)
const [triggerPrice, setTriggerPrice] = useState('')
const [orderType, setOrderType] = useState(ORDER_TYPES[0])
const [orderTypeMultiplier, setOrderTypeMultiplier] =
useState<OrderTypeMultiplier | null>(null)
const [submitting, setSubmitting] = useState(false)
const [swapFormSizeUi] = useLocalStorageState(SIZE_INPUT_UI_KEY, 'slider')
const [formErrors, setFormErrors] = useState<FormErrors>({})
const {
inputBank,
outputBank,
amountIn: amountInFormValue,
amountOut: amountOutFormValue,
flipPrices,
} = mangoStore((s) => s.swap)
const { connected, connect } = useWallet()
const { amount: tokenMax } = useTokenMax()
const [showDepositModal, setShowDepositModal] = useState(false)
const [inputBankName, outputBankName, inputBankDecimals, outputBankDecimals] =
useMemo(() => {
if (!inputBank || !outputBank) return ['', '', 0, 0]
return [
inputBank.name,
outputBank.name,
inputBank.mintDecimals,
outputBank.mintDecimals,
]
}, [inputBank, outputBank])
const amountInAsDecimal: Decimal | null = useMemo(() => {
return Number(amountInFormValue)
? new Decimal(amountInFormValue)
: new Decimal(0)
}, [amountInFormValue])
const amountOutAsDecimal: Decimal | null = useMemo(() => {
return Number(amountOutFormValue)
? new Decimal(amountOutFormValue)
: new Decimal(0)
}, [amountOutFormValue])
const freeCollateral = useMemo(() => {
const group = mangoStore.getState().group
const mangoAccount = mangoStore.getState().mangoAccount.current
return group && mangoAccount
? toUiDecimalsForQuote(mangoAccount.getCollateralValue(group))
: 0
}, [mangoAccountAddress])
const showInsufficientBalance =
tokenMax.lt(amountInAsDecimal) || tokenMax.eq(0)
const setAmountInFormValue = useCallback((amountIn: string) => {
set((s) => {
s.swap.amountIn = amountIn
if (!parseFloat(amountIn)) {
s.swap.amountOut = ''
}
})
}, [])
const setAmountOutFormValue = useCallback((amountOut: string) => {
set((s) => {
s.swap.amountOut = amountOut
if (!parseFloat(amountOut)) {
s.swap.amountIn = ''
}
})
}, [])
const quotePrice = useMemo(() => {
if (!inputBank || !outputBank) return 0
const quote = flipPrices
? floorToDecimal(
outputBank.uiPrice / inputBank.uiPrice,
inputBank.mintDecimals,
).toNumber()
: floorToDecimal(
inputBank.uiPrice / outputBank.uiPrice,
outputBank.mintDecimals,
).toNumber()
return quote
}, [flipPrices, inputBank, outputBank])
// set default trigger price
useEffect(() => {
if (!quotePrice || triggerPrice || showTokenSelect) return
const multiplier = getOrderTypeMultiplier(OrderTypes.STOP_LOSS, flipPrices)
const decimals = !flipPrices ? inputBankDecimals : outputBankDecimals
setTriggerPrice((quotePrice * multiplier).toFixed(decimals))
}, [
flipPrices,
inputBankDecimals,
outputBankDecimals,
quotePrice,
showTokenSelect,
triggerPrice,
])
// flip trigger price and set amount out when chart direction is flipped
useLayoutEffect(() => {
if (!quotePrice) return
const multiplier = getOrderTypeMultiplier(orderType, flipPrices)
const decimals = flipPrices ? inputBankDecimals : outputBankDecimals
const price = (quotePrice * multiplier).toFixed(decimals)
setTriggerPrice(price)
if (amountInAsDecimal?.gt(0)) {
const amountOut = getAmountOut(
amountInAsDecimal.toString(),
flipPrices,
price,
)
setAmountOutFormValue(amountOut.toString())
}
}, [flipPrices, inputBankDecimals, orderType, outputBankDecimals])
const triggerPriceDifference = useMemo(() => {
if (!quotePrice) return 0
const triggerDifference = triggerPrice
? ((parseFloat(triggerPrice) - quotePrice) / quotePrice) * 100
: 0
return triggerDifference
}, [quotePrice, triggerPrice])
const handleTokenSelect = (type: 'input' | 'output') => {
setShowTokenSelect(type)
setFormErrors({})
setTriggerPrice('')
}
const hasBorrowToRepay = useMemo(() => {
if (orderType !== OrderTypes.REPAY_BORROW || !outputBank || !mangoAccount)
return
const balance = mangoAccount.getTokenBalanceUi(outputBank)
const roundedBalance = floorToDecimal(
balance,
outputBank.mintDecimals,
).toNumber()
return balance && balance < 0 ? Math.abs(roundedBalance) : 0
}, [mangoAccount, orderType, outputBank])
const isFormValid = useCallback(
(form: LimitSwapForm) => {
const invalidFields: FormErrors = {}
setFormErrors({})
const requiredFields: (keyof LimitSwapForm)[] = [
'amountIn',
'triggerPrice',
]
const triggerPriceNumber = parseFloat(form.triggerPrice)
const sellTokenBalance = getSellTokenBalance(inputBank)
for (const key of requiredFields) {
const value = form[key] as string
if (!value) {
invalidFields[key] = t('settings:error-required-field')
}
}
if (orderType === OrderTypes.STOP_LOSS) {
if (flipPrices && triggerPriceNumber <= quotePrice) {
invalidFields.triggerPrice =
'Trigger price must be above oracle price'
}
if (!flipPrices && triggerPriceNumber >= quotePrice) {
invalidFields.triggerPrice =
'Trigger price must be below oracle price'
}
}
if (orderType === OrderTypes.TAKE_PROFIT) {
if (flipPrices && triggerPriceNumber >= quotePrice) {
invalidFields.triggerPrice =
'Trigger price must be below oracle price'
}
if (!flipPrices && triggerPriceNumber <= quotePrice) {
invalidFields.triggerPrice =
'Trigger price must be above oracle price'
}
}
if (orderType === OrderTypes.REPAY_BORROW && !hasBorrowToRepay) {
invalidFields.hasBorrows = t('swap:no-borrow')
}
if (form.amountIn > sellTokenBalance) {
invalidFields.amountIn = t('swap:insufficient-balance', {
symbol: inputBank?.name,
})
}
if (Object.keys(invalidFields).length) {
setFormErrors(invalidFields)
}
return invalidFields
},
[
flipPrices,
hasBorrowToRepay,
inputBank,
orderType,
quotePrice,
setFormErrors,
],
)
// set order type multiplier on page load
useEffect(() => {
if (!orderTypeMultiplier) {
const multiplier = getOrderTypeMultiplier(orderType, flipPrices)
setOrderTypeMultiplier(multiplier)
}
}, [flipPrices, orderType, orderTypeMultiplier])
// get the out amount from the in amount and trigger or limit price
const getAmountOut = useCallback(
(amountIn: string, flipPrices: boolean, price: string) => {
const amountOut = flipPrices
? floorToDecimal(
parseFloat(amountIn) / parseFloat(price),
outputBank?.mintDecimals || 0,
)
: floorToDecimal(
parseFloat(amountIn) * parseFloat(price),
outputBank?.mintDecimals || 0,
)
return amountOut
},
[outputBank],
)
// get the in amount from the out amount and trigger or limit price
const getAmountIn = useCallback(
(amountOut: string, flipPrices: boolean, price: string) => {
const amountIn = flipPrices
? floorToDecimal(
parseFloat(amountOut) * parseFloat(price),
inputBank?.mintDecimals || 0,
)
: floorToDecimal(
parseFloat(amountOut) / parseFloat(price),
inputBank?.mintDecimals || 0,
)
return amountIn
},
[inputBank, outputBank],
)
const handleMax = useCallback(
(amountIn: string) => {
setAmountInFormValue(amountIn)
if (parseFloat(amountIn) > 0 && triggerPrice) {
const amountOut = getAmountOut(amountIn, flipPrices, triggerPrice)
setAmountOutFormValue(amountOut.toString())
}
},
[
flipPrices,
getAmountOut,
setAmountInFormValue,
setAmountOutFormValue,
triggerPrice,
],
)
const handleRepay = useCallback(
(amountOut: string) => {
setAmountOutFormValue(amountOut)
if (parseFloat(amountOut) > 0 && triggerPrice) {
const amountIn = getAmountIn(amountOut, flipPrices, triggerPrice)
setAmountInFormValue(amountIn.toString())
}
},
[
flipPrices,
getAmountIn,
setAmountInFormValue,
setAmountOutFormValue,
triggerPrice,
],
)
const handleAmountInChange = useCallback(
(e: NumberFormatValues, info: SourceInfo) => {
if (info.source !== 'event') return
setFormErrors({})
setAmountInFormValue(e.value)
if (parseFloat(e.value) > 0 && triggerPrice) {
const amountOut = getAmountOut(e.value, flipPrices, triggerPrice)
setAmountOutFormValue(amountOut.toString())
}
},
[
flipPrices,
getAmountOut,
setAmountInFormValue,
setAmountOutFormValue,
setFormErrors,
triggerPrice,
],
)
const handleAmountOutChange = useCallback(
(e: NumberFormatValues, info: SourceInfo) => {
if (info.source !== 'event') return
setFormErrors({})
setAmountOutFormValue(e.value)
if (parseFloat(e.value) > 0 && triggerPrice) {
const amountIn = getAmountIn(e.value, flipPrices, triggerPrice)
setAmountInFormValue(amountIn.toString())
}
},
[
flipPrices,
getAmountIn,
setAmountInFormValue,
setAmountOutFormValue,
setFormErrors,
triggerPrice,
],
)
const handleAmountInUi = useCallback(
(amountIn: string) => {
setAmountInFormValue(amountIn)
setFormErrors({})
if (triggerPrice) {
const amountOut = getAmountOut(amountIn, flipPrices, triggerPrice)
setAmountOutFormValue(amountOut.toString())
}
},
[
flipPrices,
getAmountOut,
setAmountInFormValue,
setAmountOutFormValue,
setFormErrors,
triggerPrice,
],
)
const handleTriggerPrice = useCallback(
(e: NumberFormatValues, info: SourceInfo) => {
if (info.source !== 'event') return
setFormErrors({})
setTriggerPrice(e.value)
if (parseFloat(e.value) > 0 && parseFloat(amountInFormValue) > 0) {
const amountOut = getAmountOut(amountInFormValue, flipPrices, e.value)
setAmountOutFormValue(amountOut.toString())
}
},
[amountInFormValue, flipPrices, setFormErrors, setTriggerPrice],
)
const handleSwitchTokens = useCallback(() => {
if (!inputBank || !outputBank) return
setFormErrors({})
set((s) => {
s.swap.inputBank = outputBank
s.swap.outputBank = inputBank
})
const multiplier = getOrderTypeMultiplier(orderType, flipPrices)
const price = flipPrices
? floorToDecimal(
(inputBank.uiPrice / outputBank.uiPrice) * multiplier,
outputBank.mintDecimals,
).toString()
: floorToDecimal(
(outputBank.uiPrice / inputBank.uiPrice) * multiplier,
inputBank.mintDecimals,
).toString()
setTriggerPrice(price)
if (amountInAsDecimal?.gt(0)) {
const amountOut = getAmountOut(
amountInAsDecimal.toString(),
flipPrices,
price,
)
setAmountOutFormValue(amountOut.toString())
}
setAnimateSwitchArrow(
(prevanimateSwitchArrow) => prevanimateSwitchArrow + 1,
)
}, [
amountInAsDecimal,
flipPrices,
inputBank,
orderType,
outputBank,
setAmountInFormValue,
setFormErrors,
triggerPrice,
])
const handlePlaceStopLoss = useCallback(async () => {
const invalidFields = isFormValid({
amountIn: amountInAsDecimal.toNumber(),
hasBorrows: hasBorrowToRepay,
triggerPrice,
})
if (Object.keys(invalidFields).length) {
return
}
try {
const client = mangoStore.getState().client
const group = mangoStore.getState().group
const actions = mangoStore.getState().actions
const mangoAccount = mangoStore.getState().mangoAccount.current
const inputBank = mangoStore.getState().swap.inputBank
const outputBank = mangoStore.getState().swap.outputBank
if (!mangoAccount || !group || !inputBank || !outputBank || !triggerPrice)
return
setSubmitting(true)
const amountIn = amountInAsDecimal.toNumber()
try {
let tx
if (orderType === OrderTypes.REPAY_BORROW) {
const amountOut = amountOutAsDecimal.toNumber()
const orderPrice = parseFloat(triggerPrice)
if (quotePrice > orderPrice) {
tx = await client.tcsStopLossOnBorrow(
group,
mangoAccount,
inputBank,
outputBank,
orderPrice,
flipPrices,
amountOut,
null,
false,
null,
)
} else {
tx = await client.tcsTakeProfitOnBorrow(
group,
mangoAccount,
inputBank,
outputBank,
orderPrice,
flipPrices,
amountOut,
null,
false,
null,
)
}
}
if (orderType === OrderTypes.STOP_LOSS) {
tx = await client.tcsStopLossOnDeposit(
group,
mangoAccount,
inputBank,
outputBank,
parseFloat(triggerPrice),
flipPrices,
amountIn,
null,
null,
)
}
if (orderType === OrderTypes.TAKE_PROFIT) {
tx = await client.tcsTakeProfitOnDeposit(
group,
mangoAccount,
inputBank,
outputBank,
parseFloat(triggerPrice),
flipPrices,
amountIn,
null,
null,
)
}
notify({
title: 'Transaction confirmed',
type: 'success',
txid: tx?.signature,
noSound: true,
})
actions.fetchGroup()
await actions.reloadMangoAccount(tx?.slot)
} catch (e) {
console.error('onSwap error: ', e)
sentry.captureException(e)
if (isMangoError(e)) {
notify({
title: 'Transaction failed',
description: e.message,
txid: e?.txid,
type: 'error',
})
}
}
} catch (e) {
console.error('Swap error:', e)
} finally {
setSubmitting(false)
}
}, [
hasBorrowToRepay,
flipPrices,
orderType,
quotePrice,
triggerPrice,
amountInAsDecimal,
amountOutFormValue,
])
const orderDescription = useMemo(() => {
if (
!amountInFormValue ||
!amountOutFormValue ||
!inputBankName ||
!outputBankName ||
!triggerPrice
)
return
const quoteString = flipPrices
? `${inputBankName} per ${outputBankName}`
: `${outputBankName} per ${inputBankName}`
if (hasBorrowToRepay && orderType === OrderTypes.REPAY_BORROW) {
const amountOut = floorToDecimal(
amountOutFormValue,
outputBankDecimals,
).toNumber()
if (amountOut <= hasBorrowToRepay) {
return t('trade:repay-borrow-order-desc', {
amount: amountOut,
priceUnit: quoteString,
symbol: outputBankName,
triggerPrice: floorToDecimal(triggerPrice, inputBankDecimals),
})
} else {
const depositAmount = floorToDecimal(
amountOut - hasBorrowToRepay,
outputBankDecimals,
).toNumber()
return t('trade:repay-borrow-deposit-order-desc', {
borrowAmount: hasBorrowToRepay,
depositAmount: depositAmount,
priceUnit: quoteString,
symbol: outputBankName,
triggerPrice: floorToDecimal(triggerPrice, inputBankDecimals),
})
}
} else {
const orderTypeString =
orderType === OrderTypes.STOP_LOSS
? !flipPrices
? t('trade:falls-to')
: t('trade:rises-to')
: !flipPrices
? t('trade:rises-to')
: t('trade:falls-to')
return t('trade:trigger-order-desc', {
amount: floorToDecimal(amountInFormValue, inputBankDecimals),
orderType: orderTypeString,
priceUnit: quoteString,
symbol: inputBankName,
triggerPrice: floorToDecimal(triggerPrice, inputBankDecimals),
})
}
}, [
amountInFormValue,
amountOutFormValue,
flipPrices,
hasBorrowToRepay,
inputBankDecimals,
inputBankName,
orderType,
outputBankDecimals,
outputBankName,
triggerPrice,
])
const triggerPriceSuffix = useMemo(() => {
if (!inputBankName || !outputBankName) return
if (flipPrices) {
return `${inputBankName} per ${outputBankName}`
} else {
return `${outputBankName} per ${inputBankName}`
}
}, [flipPrices, inputBankName, outputBankName])
const toggleFlipPrices = useCallback(
(flip: boolean) => {
if (!inputBankName || !outputBankName) return
setFormErrors({})
set((state) => {
state.swap.flipPrices = flip
})
},
[inputBankName, outputBankName, setFormErrors],
)
const handleOrderTypeChange = useCallback(
(type: string) => {
setFormErrors({})
const newType = type as OrderTypes
setOrderType(newType)
const triggerMultiplier = getOrderTypeMultiplier(newType, flipPrices)
setOrderTypeMultiplier(triggerMultiplier)
const trigger = (quotePrice * triggerMultiplier).toString()
setTriggerPrice(trigger)
if (amountInAsDecimal.gt(0)) {
const amountOut = getAmountOut(
amountInAsDecimal.toString(),
flipPrices,
trigger,
).toString()
setAmountOutFormValue(amountOut)
}
},
[flipPrices, quotePrice, setFormErrors, setOrderTypeMultiplier],
)
const onClick = !connected
? connect
: showInsufficientBalance || freeCollateral <= 0
? () => setShowDepositModal(true)
: handlePlaceStopLoss
return (
<>
<SellTokenInput
className="rounded-b-none"
error={formErrors.amountIn}
handleAmountInChange={handleAmountInChange}
setShowTokenSelect={() => handleTokenSelect('input')}
handleMax={handleMax}
isTriggerOrder
/>
<div
className={`grid grid-cols-2 gap-2 rounded-b-xl bg-th-bkg-2 p-3 pt-1`}
id="swap-step-two"
>
<div className="col-span-1">
<p className="mb-2 text-th-fgd-2">{t('trade:order-type')}</p>
<Select
value={t(orderType)}
onChange={(type) => handleOrderTypeChange(type)}
className="w-full"
buttonClassName="ring-transparent rounded-t-lg rounded-b-lg focus:outline-none md:hover:bg-th-bkg-1 md:hover:ring-transparent focus-visible:bg-th-bkg-3 whitespace-nowrap"
>
{ORDER_TYPES.map((type) => (
<Select.Option key={type} value={type}>
{t(type)}
</Select.Option>
))}
</Select>
</div>
<div className="col-span-1">
<div className="mb-2 flex items-end justify-between">
<p className="text-th-fgd-2">{t('trade:trigger-price')}</p>
<p
className={`font-mono text-xs ${
triggerPriceDifference >= 0 ? 'text-th-up' : 'text-th-down'
}`}
>
{triggerPriceDifference
? triggerPriceDifference.toFixed(2)
: '0.00'}
%
</p>
</div>
<div className="flex items-center">
<div className="relative w-full">
<NumberFormat
inputMode="decimal"
thousandSeparator=","
allowNegative={false}
isNumericString={true}
decimalScale={
flipPrices ? inputBankDecimals : outputBankDecimals || 6
}
name="triggerPrice"
id="triggerPrice"
className="h-10 w-full rounded-lg bg-th-input-bkg p-3 pl-8 font-mono text-sm text-th-fgd-1 focus:outline-none md:hover:bg-th-bkg-1"
placeholder="0.00"
value={triggerPrice}
onValueChange={handleTriggerPrice}
isAllowed={withValueLimit}
/>
<div className="absolute top-1/2 -translate-y-1/2 left-2">
<TokenLogo
bank={flipPrices ? inputBank : outputBank}
size={16}
/>
</div>
</div>
</div>
<div className="flex justify-end">
<LinkButton
className="flex items-center font-normal text-xxs text-th-fgd-3"
onClick={() => toggleFlipPrices(!flipPrices)}
>
<span className="mr-1">{triggerPriceSuffix}</span>
<ArrowsRightLeftIcon className="h-3.5 w-3.5" />
</LinkButton>
</div>
</div>
{formErrors.triggerPrice ? (
<div className="col-span-2 flex justify-center">
<InlineNotification
type="error"
desc={formErrors.triggerPrice}
hideBorder
hidePadding
/>
</div>
) : null}
</div>
<div className="my-2 flex justify-center">
<button
className="rounded-full border border-th-fgd-4 p-1.5 text-th-fgd-3 focus-visible:border-th-active md:hover:border-th-active md:hover:text-th-active"
onClick={handleSwitchTokens}
>
<ArrowDownIcon
className="h-5 w-5"
style={
animateSwitchArrow % 2 == 0
? { transform: 'rotate(0deg)' }
: { transform: 'rotate(360deg)' }
}
/>
</button>
</div>
<BuyTokenInput
error={formErrors.hasBorrows}
handleAmountOutChange={handleAmountOutChange}
setShowTokenSelect={() => handleTokenSelect('output')}
handleRepay={
orderType === OrderTypes.REPAY_BORROW ? handleRepay : undefined
}
/>
{swapFormSizeUi === 'slider' ? (
<SwapSlider
useMargin={false}
amount={amountInAsDecimal.toNumber()}
onChange={(v) => handleAmountInUi(v)}
step={1 / 10 ** (inputBankDecimals || 6)}
/>
) : (
<PercentageSelectButtons
amountIn={amountInAsDecimal.toString()}
setAmountIn={(v) => handleAmountInUi(v)}
useMargin={false}
/>
)}
{orderType === OrderTypes.REPAY_BORROW &&
!hasBorrowToRepay ? null : orderDescription ? (
<div className="mt-4">
<InlineNotification
desc={
<>
{orderType !== OrderTypes.REPAY_BORROW ? (
<>
<span className="text-th-down">{t('sell')}</span>{' '}
</>
) : null}
{orderDescription}
</>
}
type="info"
/>
</div>
) : null}
{ipAllowed ? (
<Button
onClick={onClick}
className="mt-6 mb-4 flex w-full items-center justify-center text-base"
size="large"
>
{connected ? (
showInsufficientBalance || freeCollateral <= 0 ? (
<div className="flex items-center">
<ArrowDownTrayIcon className="mr-2 h-5 w-5 flex-shrink-0" />
{t('swap:deposit-funds')}
</div>
) : submitting ? (
<Loading />
) : (
<span>{t('swap:place-limit-order')}</span>
)
) : (
<div className="flex items-center">
<LinkIcon className="mr-2 h-5 w-5" />
{t('connect')}
</div>
)}
</Button>
) : (
<Button
disabled
className="mt-6 mb-4 w-full leading-tight"
size="large"
>
{t('country-not-allowed', {
country: ipCountry ? `(${ipCountry})` : '',
})}
</Button>
)}
{showDepositModal ? (
<DepositWithdrawModal
action="deposit"
isOpen={showDepositModal}
onClose={() => setShowDepositModal(false)}
token={freeCollateral > 0 ? inputBankName : ''}
/>
) : null}
</>
)
}
export default LimitSwapForm

View File

@ -0,0 +1,433 @@
import {
useState,
useCallback,
useEffect,
useMemo,
Dispatch,
SetStateAction,
} from 'react'
import {
ArrowDownIcon,
ArrowDownTrayIcon,
LinkIcon,
} from '@heroicons/react/20/solid'
import { NumberFormatValues, SourceInfo } from 'react-number-format'
import Decimal from 'decimal.js'
import mangoStore from '@store/mangoStore'
import useDebounce from '../shared/useDebounce'
import { MANGO_MINT, SIZE_INPUT_UI_KEY, USDC_MINT } from '../../utils/constants'
import { useWallet } from '@solana/wallet-adapter-react'
import { RouteInfo } from 'types/jupiter'
import useLocalStorageState from 'hooks/useLocalStorageState'
import SwapSlider from './SwapSlider'
import PercentageSelectButtons from './PercentageSelectButtons'
import BuyTokenInput from './BuyTokenInput'
import SellTokenInput from './SellTokenInput'
import Button from '@components/shared/Button'
import { Transition } from '@headlessui/react'
import SwapReviewRouteInfo from './SwapReviewRouteInfo'
import useIpAddress from 'hooks/useIpAddress'
import { useTranslation } from 'react-i18next'
import useQuoteRoutes from './useQuoteRoutes'
import { useTokenMax } from './useTokenMax'
import Loading from '@components/shared/Loading'
import InlineNotification from '@components/shared/InlineNotification'
import useMangoAccount from 'hooks/useMangoAccount'
import { toUiDecimalsForQuote } from '@blockworks-foundation/mango-v4'
import DepositWithdrawModal from '@components/modals/DepositWithdrawModal'
import useMangoAccountAccounts from 'hooks/useMangoAccountAccounts'
import Link from 'next/link'
type MarketSwapFormProps = {
setShowTokenSelect: Dispatch<SetStateAction<'input' | 'output' | undefined>>
}
const MAX_DIGITS = 11
export const withValueLimit = (values: NumberFormatValues): boolean => {
return values.floatValue
? values.floatValue.toFixed(0).length <= MAX_DIGITS
: true
}
export const NUMBER_FORMAT_CLASSNAMES =
'w-full rounded-r-lg h-[56px] box-border pb-4 border-l border-th-bkg-2 bg-th-input-bkg px-3 text-right font-mono text-xl text-th-fgd-1 focus:outline-none md:hover:bg-th-bkg-1'
const set = mangoStore.getState().set
const MarketSwapForm = ({ setShowTokenSelect }: MarketSwapFormProps) => {
const { t } = useTranslation(['common', 'swap', 'trade'])
//initial state is undefined null is returned on error
const [selectedRoute, setSelectedRoute] = useState<RouteInfo | null>()
const [animateSwitchArrow, setAnimateSwitchArrow] = useState(0)
const [showConfirm, setShowConfirm] = useState(false)
const [swapFormSizeUi] = useLocalStorageState(SIZE_INPUT_UI_KEY, 'slider')
const {
margin: useMargin,
slippage,
inputBank,
outputBank,
amountIn: amountInFormValue,
amountOut: amountOutFormValue,
swapMode,
} = mangoStore((s) => s.swap)
const [debouncedAmountIn] = useDebounce(amountInFormValue, 300)
const [debouncedAmountOut] = useDebounce(amountOutFormValue, 300)
const { connected, publicKey } = useWallet()
const { bestRoute, routes } = useQuoteRoutes({
inputMint: inputBank?.mint.toString() || USDC_MINT,
outputMint: outputBank?.mint.toString() || MANGO_MINT,
amount: swapMode === 'ExactIn' ? debouncedAmountIn : debouncedAmountOut,
slippage,
swapMode,
wallet: publicKey?.toBase58(),
})
const { ipAllowed, ipCountry } = useIpAddress()
const amountInAsDecimal: Decimal | null = useMemo(() => {
return Number(debouncedAmountIn)
? new Decimal(debouncedAmountIn)
: new Decimal(0)
}, [debouncedAmountIn])
const amountOutAsDecimal: Decimal | null = useMemo(() => {
return Number(debouncedAmountOut)
? new Decimal(debouncedAmountOut)
: new Decimal(0)
}, [debouncedAmountOut])
const setAmountInFormValue = useCallback(
(amountIn: string, setSwapMode?: boolean) => {
set((s) => {
s.swap.amountIn = amountIn
if (!parseFloat(amountIn)) {
s.swap.amountOut = ''
}
if (setSwapMode) {
s.swap.swapMode = 'ExactIn'
}
})
},
[],
)
const setAmountOutFormValue = useCallback(
(amountOut: string, setSwapMode?: boolean) => {
set((s) => {
s.swap.amountOut = amountOut
if (!parseFloat(amountOut)) {
s.swap.amountIn = ''
}
if (setSwapMode) {
s.swap.swapMode = 'ExactOut'
}
})
},
[],
)
const handleAmountInChange = useCallback(
(e: NumberFormatValues, info: SourceInfo) => {
if (info.source !== 'event') return
setAmountInFormValue(e.value)
if (swapMode === 'ExactOut') {
set((s) => {
s.swap.swapMode = 'ExactIn'
})
}
},
[outputBank, setAmountInFormValue, swapMode],
)
const handleAmountOutChange = useCallback(
(e: NumberFormatValues, info: SourceInfo) => {
if (info.source !== 'event') return
if (swapMode === 'ExactIn') {
set((s) => {
s.swap.swapMode = 'ExactOut'
})
}
setAmountOutFormValue(e.value)
},
[swapMode, setAmountOutFormValue],
)
const handleMax = useCallback(
(amountIn: string) => {
setAmountInFormValue(amountIn, true)
},
[setAmountInFormValue],
)
const handleRepay = useCallback(
(amountOut: string) => {
setAmountOutFormValue(amountOut, true)
},
[setAmountInFormValue],
)
/*
Once a route is returned from the Jupiter API, use the inAmount or outAmount
depending on the swapMode and set those values in state
*/
useEffect(() => {
if (typeof bestRoute !== 'undefined') {
setSelectedRoute(bestRoute)
if (inputBank && swapMode === 'ExactOut' && bestRoute) {
const inAmount = new Decimal(bestRoute!.inAmount)
.div(10 ** inputBank.mintDecimals)
.toString()
setAmountInFormValue(inAmount)
} else if (outputBank && swapMode === 'ExactIn' && bestRoute) {
const outAmount = new Decimal(bestRoute!.outAmount)
.div(10 ** outputBank.mintDecimals)
.toString()
setAmountOutFormValue(outAmount)
}
}
}, [bestRoute, swapMode, inputBank, outputBank])
/*
If the use margin setting is toggled, clear the form values
*/
useEffect(() => {
setAmountInFormValue('')
setAmountOutFormValue('')
}, [useMargin, setAmountInFormValue, setAmountOutFormValue])
const handleSwitchTokens = useCallback(() => {
if (amountInAsDecimal?.gt(0) && amountOutAsDecimal.gte(0)) {
setAmountInFormValue(amountOutAsDecimal.toString())
}
const inputBank = mangoStore.getState().swap.inputBank
const outputBank = mangoStore.getState().swap.outputBank
set((s) => {
s.swap.inputBank = outputBank
s.swap.outputBank = inputBank
})
setAnimateSwitchArrow(
(prevanimateSwitchArrow) => prevanimateSwitchArrow + 1,
)
}, [setAmountInFormValue, amountOutAsDecimal, amountInAsDecimal])
const loadingSwapDetails: boolean = useMemo(() => {
return (
!!(amountInAsDecimal.toNumber() || amountOutAsDecimal.toNumber()) &&
connected &&
typeof selectedRoute === 'undefined'
)
}, [amountInAsDecimal, amountOutAsDecimal, connected, selectedRoute])
return (
<>
<div>
<Transition
className="absolute top-0 right-0 z-10 h-full w-full bg-th-bkg-1 pb-0"
show={showConfirm}
enter="transition ease-in duration-300"
enterFrom="-translate-x-full"
enterTo="translate-x-0"
leave="transition ease-out duration-300"
leaveFrom="translate-x-0"
leaveTo="-translate-x-full"
>
<SwapReviewRouteInfo
onClose={() => setShowConfirm(false)}
amountIn={amountInAsDecimal}
slippage={slippage}
routes={routes}
selectedRoute={selectedRoute}
setSelectedRoute={setSelectedRoute}
/>
</Transition>
</div>
<SellTokenInput
handleAmountInChange={handleAmountInChange}
setShowTokenSelect={setShowTokenSelect}
handleMax={handleMax}
/>
<div className="my-2 flex justify-center">
<button
className="rounded-full border border-th-fgd-4 p-1.5 text-th-fgd-3 focus-visible:border-th-active md:hover:border-th-active md:hover:text-th-active"
onClick={handleSwitchTokens}
>
<ArrowDownIcon
className="h-5 w-5"
style={
animateSwitchArrow % 2 == 0
? { transform: 'rotate(0deg)' }
: { transform: 'rotate(360deg)' }
}
/>
</button>
</div>
<BuyTokenInput
handleAmountOutChange={handleAmountOutChange}
loading={loadingSwapDetails}
setShowTokenSelect={setShowTokenSelect}
handleRepay={handleRepay}
/>
{swapFormSizeUi === 'slider' ? (
<SwapSlider
useMargin={useMargin}
amount={amountInAsDecimal.toNumber()}
onChange={(v) => setAmountInFormValue(v, true)}
step={1 / 10 ** (inputBank?.mintDecimals || 6)}
/>
) : (
<PercentageSelectButtons
amountIn={amountInAsDecimal.toString()}
setAmountIn={(v) => setAmountInFormValue(v, true)}
useMargin={useMargin}
/>
)}
{ipAllowed ? (
<SwapFormSubmitButton
loadingSwapDetails={loadingSwapDetails}
useMargin={useMargin}
selectedRoute={selectedRoute}
setShowConfirm={setShowConfirm}
amountIn={amountInAsDecimal}
inputSymbol={inputBank?.name}
amountOut={selectedRoute ? amountOutAsDecimal.toNumber() : undefined}
/>
) : (
<Button
disabled
className="mt-6 mb-4 w-full leading-tight"
size="large"
>
{t('country-not-allowed', {
country: ipCountry ? `(${ipCountry})` : '',
})}
</Button>
)}
</>
)
}
export default MarketSwapForm
const SwapFormSubmitButton = ({
amountIn,
amountOut,
inputSymbol,
loadingSwapDetails,
selectedRoute,
setShowConfirm,
useMargin,
}: {
amountIn: Decimal
amountOut: number | undefined
inputSymbol: string | undefined
loadingSwapDetails: boolean
selectedRoute: RouteInfo | undefined | null
setShowConfirm: (x: boolean) => void
useMargin: boolean
}) => {
const { t } = useTranslation('common')
const { mangoAccountAddress } = useMangoAccount()
const { connected, connect } = useWallet()
const { amount: tokenMax, amountWithBorrow } = useTokenMax(useMargin)
const [showDepositModal, setShowDepositModal] = useState(false)
const { usedTokens, totalTokens } = useMangoAccountAccounts()
const { inputBank, outputBank } = mangoStore((s) => s.swap)
const tokenPositionsFull = useMemo(() => {
if (!inputBank || !outputBank || !usedTokens.length || !totalTokens.length)
return false
const hasInputTokenPosition = usedTokens.find(
(token) => token.tokenIndex === inputBank.tokenIndex,
)
const hasOutputTokenPosition = usedTokens.find(
(token) => token.tokenIndex === outputBank.tokenIndex,
)
if (
(hasInputTokenPosition && hasOutputTokenPosition) ||
totalTokens.length - usedTokens.length >= 2
) {
return false
} else return true
}, [inputBank, outputBank, usedTokens, totalTokens])
const freeCollateral = useMemo(() => {
const group = mangoStore.getState().group
const mangoAccount = mangoStore.getState().mangoAccount.current
return group && mangoAccount
? toUiDecimalsForQuote(mangoAccount.getCollateralValue(group))
: 0
}, [mangoAccountAddress])
const showInsufficientBalance = useMargin
? amountWithBorrow.lt(amountIn) || amountWithBorrow.eq(0)
: tokenMax.lt(amountIn) || tokenMax.eq(0)
const disabled =
connected &&
!showInsufficientBalance &&
freeCollateral > 0 &&
(!amountIn.toNumber() || !amountOut || !selectedRoute || tokenPositionsFull)
const onClick = !connected
? connect
: showInsufficientBalance || freeCollateral <= 0
? () => setShowDepositModal(true)
: () => setShowConfirm(true)
return (
<>
<Button
onClick={onClick}
className="mt-6 mb-4 flex w-full items-center justify-center text-base"
disabled={disabled}
size="large"
>
{connected ? (
showInsufficientBalance || freeCollateral <= 0 ? (
<div className="flex items-center">
<ArrowDownTrayIcon className="mr-2 h-5 w-5 flex-shrink-0" />
{t('swap:deposit-funds')}
</div>
) : loadingSwapDetails ? (
<Loading />
) : (
<span>{t('swap:review-swap')}</span>
)
) : (
<div className="flex items-center">
<LinkIcon className="mr-2 h-5 w-5" />
{t('connect')}
</div>
)}
</Button>
{tokenPositionsFull ? (
<div className="pb-4">
<InlineNotification
type="error"
desc={
<>
{t('error-token-positions-full')}{' '}
<Link href="/settings" shallow>
{t('manage')}
</Link>
</>
}
/>
</div>
) : null}
{selectedRoute === null && amountIn.gt(0) ? (
<div className="mb-4">
<InlineNotification type="error" desc={t('swap:no-swap-found')} />
</div>
) : null}
{showDepositModal ? (
<DepositWithdrawModal
action="deposit"
isOpen={showDepositModal}
onClose={() => setShowDepositModal(false)}
token={freeCollateral > 0 ? inputSymbol : ''}
/>
) : null}
</>
)
}

View File

@ -33,7 +33,7 @@ const MaxSwapAmount = ({
<MaxAmountButton
className="mb-0.5"
decimals={decimals}
label={t('bal')}
label={useMargin ? t('bal') : t('max')}
onClick={() => setMax(tokenMax)}
value={tokenMax}
/>

View File

@ -0,0 +1,123 @@
import TokenSelect from './TokenSelect'
import NumberFormat, {
NumberFormatValues,
SourceInfo,
} from 'react-number-format'
import { formatCurrencyValue } from 'utils/numbers'
import { useTranslation } from 'react-i18next'
import { Dispatch, SetStateAction, useMemo } from 'react'
import mangoStore from '@store/mangoStore'
import useMangoGroup from 'hooks/useMangoGroup'
import { INPUT_TOKEN_DEFAULT } from 'utils/constants'
import { NUMBER_FORMAT_CLASSNAMES, withValueLimit } from './MarketSwapForm'
import MaxSwapAmount from './MaxSwapAmount'
import useUnownedAccount from 'hooks/useUnownedAccount'
import InlineNotification from '@components/shared/InlineNotification'
import useMangoAccount from 'hooks/useMangoAccount'
import { useWallet } from '@solana/wallet-adapter-react'
import { toUiDecimalsForQuote } from '@blockworks-foundation/mango-v4'
const SellTokenInput = ({
handleAmountInChange,
setShowTokenSelect,
handleMax,
className,
error,
isTriggerOrder,
}: {
handleAmountInChange: (e: NumberFormatValues, info: SourceInfo) => void
setShowTokenSelect: Dispatch<SetStateAction<'input' | 'output' | undefined>>
handleMax: (amountIn: string) => void
className?: string
error?: string
isTriggerOrder?: boolean
}) => {
const { t } = useTranslation('common')
const { mangoAccountAddress } = useMangoAccount()
const { connected } = useWallet()
const { group } = useMangoGroup()
const { isUnownedAccount } = useUnownedAccount()
const {
margin: useMargin,
inputBank,
amountIn: amountInFormValue,
} = mangoStore((s) => s.swap)
const freeCollateral = useMemo(() => {
const group = mangoStore.getState().group
const mangoAccount = mangoStore.getState().mangoAccount.current
return group && mangoAccount
? toUiDecimalsForQuote(mangoAccount.getCollateralValue(group))
: 0
}, [mangoAccountAddress])
return (
<div className={`grid grid-cols-2 rounded-xl bg-th-bkg-2 p-3 ${className}`}>
<div className="col-span-2 mb-2 flex items-center justify-between">
<p className="text-th-fgd-2">{t('sell')}</p>
{!isUnownedAccount ? (
<MaxSwapAmount
useMargin={isTriggerOrder ? false : useMargin}
setAmountIn={(v) => handleMax(v)}
/>
) : null}
</div>
<div className="col-span-1">
<TokenSelect
bank={
inputBank || group?.banksMapByName.get(INPUT_TOKEN_DEFAULT)?.[0]
}
showTokenList={setShowTokenSelect}
type="input"
/>
</div>
<div className="relative col-span-1">
<NumberFormat
inputMode="decimal"
thousandSeparator=","
allowNegative={false}
isNumericString={true}
decimalScale={inputBank?.mintDecimals || 6}
name="amountIn"
id="amountIn"
className={NUMBER_FORMAT_CLASSNAMES}
placeholder="0.00"
value={amountInFormValue}
onValueChange={handleAmountInChange}
isAllowed={withValueLimit}
/>
{!isNaN(Number(amountInFormValue)) ? (
<span className="absolute right-3 bottom-1.5 text-xxs text-th-fgd-4">
{inputBank
? formatCurrencyValue(
inputBank.uiPrice * Number(amountInFormValue),
)
: ''}
</span>
) : null}
</div>
{connected && freeCollateral <= 0 ? (
<div className="col-span-2 mt-1 flex justify-center">
<InlineNotification
type="warning"
desc={t('swap:warning-no-collateral')}
hideBorder
hidePadding
/>
</div>
) : null}
{error ? (
<div className="col-span-2 mt-1 flex justify-center">
<InlineNotification
type="error"
desc={error}
hideBorder
hidePadding
/>
</div>
) : null}
</div>
)
}
export default SellTokenInput

View File

@ -1,86 +1,38 @@
import { useState, useCallback, useEffect, useMemo } from 'react'
import { useState, useCallback, useMemo, useEffect } from 'react'
import { PublicKey } from '@solana/web3.js'
import {
ArrowDownIcon,
Cog8ToothIcon,
ExclamationCircleIcon,
LinkIcon,
} from '@heroicons/react/20/solid'
import NumberFormat, {
NumberFormatValues,
SourceInfo,
} from 'react-number-format'
import Decimal from 'decimal.js'
import { PencilIcon } from '@heroicons/react/20/solid'
import mangoStore from '@store/mangoStore'
import ContentBox from '../shared/ContentBox'
import SwapReviewRouteInfo from './SwapReviewRouteInfo'
import TokenSelect from './TokenSelect'
import { useTranslation } from 'next-i18next'
import SwapFormTokenList from './SwapFormTokenList'
import { Transition } from '@headlessui/react'
import Button, { IconButton, LinkButton } from '../shared/Button'
import Loading from '../shared/Loading'
import { LinkButton } from '../shared/Button'
import { EnterBottomExitBottom } from '../shared/Transitions'
import useQuoteRoutes from './useQuoteRoutes'
import { HealthType } from '@blockworks-foundation/mango-v4'
import {
INPUT_TOKEN_DEFAULT,
MANGO_MINT,
OUTPUT_TOKEN_DEFAULT,
SIZE_INPUT_UI_KEY,
SWAP_MARGIN_KEY,
USDC_MINT,
} from '../../utils/constants'
import { useTokenMax } from './useTokenMax'
import { SWAP_MARGIN_KEY } from '../../utils/constants'
import HealthImpact from '@components/shared/HealthImpact'
import { useWallet } from '@solana/wallet-adapter-react'
import useMangoAccount from 'hooks/useMangoAccount'
import { RouteInfo } from 'types/jupiter'
import useMangoGroup from 'hooks/useMangoGroup'
import useLocalStorageState from 'hooks/useLocalStorageState'
import SwapSlider from './SwapSlider'
import TokenVaultWarnings from '@components/shared/TokenVaultWarnings'
import MaxSwapAmount from './MaxSwapAmount'
import PercentageSelectButtons from './PercentageSelectButtons'
import useIpAddress from 'hooks/useIpAddress'
import SwapSettings from './SwapSettings'
import InlineNotification from '@components/shared/InlineNotification'
import useUnownedAccount from 'hooks/useUnownedAccount'
import Tooltip from '@components/shared/Tooltip'
import { formatCurrencyValue } from 'utils/numbers'
import TabUnderline from '@components/shared/TabUnderline'
import MarketSwapForm from './MarketSwapForm'
import LimitSwapForm from './LimitSwapForm'
import Switch from '@components/forms/Switch'
import MaxAmountButton from '@components/shared/MaxAmountButton'
import useMangoAccountAccounts from 'hooks/useMangoAccountAccounts'
import Link from 'next/link'
const MAX_DIGITS = 11
export const withValueLimit = (values: NumberFormatValues): boolean => {
return values.floatValue
? values.floatValue.toFixed(0).length <= MAX_DIGITS
: true
}
const NUMBER_FORMAT_CLASSNAMES =
'w-full rounded-r-lg border h-[56px] border-th-input-border bg-th-input-bkg px-3 pb-4 border-box text-right font-mono text-xl text-th-fgd-1 focus:border-th-fgd-4 focus:outline-none md:hover:border-th-input-border-hover md:hover:focus-visible:border-th-fgd-4'
import useLocalStorageState from 'hooks/useLocalStorageState'
import { useIsWhiteListed } from 'hooks/useIsWhiteListed'
const set = mangoStore.getState().set
const SwapForm = () => {
const { t } = useTranslation(['common', 'swap', 'trade'])
//initial state is undefined null is returned on error
const [selectedRoute, setSelectedRoute] = useState<RouteInfo | null>()
const [animateSwitchArrow, setAnimateSwitchArrow] = useState(0)
const { data: isWhiteListed } = useIsWhiteListed()
const [showTokenSelect, setShowTokenSelect] = useState<'input' | 'output'>()
const [showSettings, setShowSettings] = useState(false)
const [showConfirm, setShowConfirm] = useState(false)
const { group } = useMangoGroup()
const [swapFormSizeUi] = useLocalStorageState(SIZE_INPUT_UI_KEY, 'slider')
const [swapOrLimit, setSwapOrLimit] = useState('swap')
const [, setSavedSwapMargin] = useLocalStorageState<boolean>(
SWAP_MARGIN_KEY,
true,
)
const { ipAllowed, ipCountry } = useIpAddress()
const { isUnownedAccount, isDelegatedAccount } = useUnownedAccount()
const {
margin: useMargin,
@ -89,131 +41,7 @@ const SwapForm = () => {
outputBank,
amountIn: amountInFormValue,
amountOut: amountOutFormValue,
swapMode,
} = mangoStore((s) => s.swap)
const { mangoAccount } = useMangoAccount()
const { connected, publicKey } = useWallet()
const amountInAsDecimal: Decimal | null = useMemo(() => {
return Number(amountInFormValue)
? new Decimal(amountInFormValue)
: new Decimal(0)
}, [amountInFormValue])
const amountOutAsDecimal: Decimal | null = useMemo(() => {
return Number(amountOutFormValue)
? new Decimal(amountOutFormValue)
: new Decimal(0)
}, [amountOutFormValue])
const { bestRoute, routes } = useQuoteRoutes({
inputMint: inputBank?.mint.toString() || USDC_MINT,
outputMint: outputBank?.mint.toString() || MANGO_MINT,
amount: swapMode === 'ExactIn' ? amountInFormValue : amountOutFormValue,
slippage,
swapMode,
wallet: publicKey?.toBase58(),
mode: isDelegatedAccount ? 'JUPITER' : 'ALL',
})
const setAmountInFormValue = useCallback(
(amountIn: string, setSwapMode?: boolean) => {
set((s) => {
s.swap.amountIn = amountIn
if (!parseFloat(amountIn)) {
s.swap.amountOut = ''
}
if (setSwapMode) {
s.swap.swapMode = 'ExactIn'
}
})
},
[],
)
const setAmountFromSlider = useCallback(
(amount: string) => {
setAmountInFormValue(amount, true)
},
[setAmountInFormValue],
)
const setAmountOutFormValue = useCallback((amountOut: string) => {
set((s) => {
s.swap.amountOut = amountOut
if (!parseFloat(amountOut)) {
s.swap.amountIn = ''
}
})
}, [])
const setBorrowAmountOut = useCallback(
(borrowAmount: string) => {
if (swapMode === 'ExactIn') {
set((s) => {
s.swap.swapMode = 'ExactOut'
})
}
setAmountOutFormValue(borrowAmount.toString())
},
[setAmountOutFormValue],
)
/*
Once a route is returned from the Jupiter API, use the inAmount or outAmount
depending on the swapMode and set those values in state
*/
useEffect(() => {
if (typeof bestRoute !== 'undefined') {
setSelectedRoute(bestRoute)
if (inputBank && swapMode === 'ExactOut' && bestRoute) {
const inAmount = new Decimal(bestRoute!.inAmount)
.div(10 ** inputBank.mintDecimals)
.toString()
setAmountInFormValue(inAmount)
} else if (outputBank && swapMode === 'ExactIn' && bestRoute) {
const outAmount = new Decimal(bestRoute!.outAmount)
.div(10 ** outputBank.mintDecimals)
.toString()
setAmountOutFormValue(outAmount)
}
}
}, [bestRoute, swapMode, inputBank, outputBank])
/*
If the use margin setting is toggled, clear the form values
*/
useEffect(() => {
setAmountInFormValue('')
setAmountOutFormValue('')
}, [useMargin, setAmountInFormValue, setAmountOutFormValue])
const handleAmountInChange = useCallback(
(e: NumberFormatValues, info: SourceInfo) => {
if (info.source !== 'event') return
if (swapMode === 'ExactOut') {
set((s) => {
s.swap.swapMode = 'ExactIn'
})
}
setAmountInFormValue(e.value)
},
[swapMode, setAmountInFormValue],
)
const handleAmountOutChange = useCallback(
(e: NumberFormatValues, info: SourceInfo) => {
if (info.source !== 'event') return
if (swapMode === 'ExactIn') {
set((s) => {
s.swap.swapMode = 'ExactOut'
})
}
setAmountOutFormValue(e.value)
},
[swapMode, setAmountOutFormValue],
)
const handleTokenInSelect = useCallback((mintAddress: string) => {
const group = mangoStore.getState().group
@ -237,34 +65,18 @@ const SwapForm = () => {
setShowTokenSelect(undefined)
}, [])
const handleSwitchTokens = useCallback(
(amountIn: Decimal, amountOut: Decimal) => {
if (amountIn?.gt(0) && amountOut.gte(0)) {
setAmountInFormValue(amountOut.toString())
}
const inputBank = mangoStore.getState().swap.inputBank
const outputBank = mangoStore.getState().swap.outputBank
set((s) => {
s.swap.inputBank = outputBank
s.swap.outputBank = inputBank
})
setAnimateSwitchArrow(
(prevanimateSwitchArrow) => prevanimateSwitchArrow + 1,
)
},
[setAmountInFormValue],
)
const maintProjectedHealth = useMemo(() => {
const group = mangoStore.getState().group
const mangoAccount = mangoStore.getState().mangoAccount.current
if (
!inputBank ||
!mangoAccount ||
!outputBank ||
!amountOutAsDecimal ||
!amountInFormValue ||
!amountOutFormValue ||
!group
)
return 0
return 100
const simulatedHealthRatio =
mangoAccount.simHealthRatioWithTokenPositionUiChanges(
@ -272,11 +84,11 @@ const SwapForm = () => {
[
{
mintPk: inputBank.mint,
uiTokenAmount: amountInAsDecimal.toNumber() * -1,
uiTokenAmount: parseFloat(amountInFormValue) * -1,
},
{
mintPk: outputBank.mint,
uiTokenAmount: amountOutAsDecimal.toNumber(),
uiTokenAmount: parseFloat(amountOutFormValue),
},
],
HealthType.maint,
@ -286,27 +98,14 @@ const SwapForm = () => {
: simulatedHealthRatio < 0
? 0
: Math.trunc(simulatedHealthRatio)
}, [
mangoAccount,
inputBank,
outputBank,
amountInAsDecimal,
amountOutAsDecimal,
])
}, [inputBank, outputBank, amountInFormValue, amountOutFormValue])
const outputTokenBalanceBorrow = useMemo(() => {
if (!outputBank) return 0
const balance = mangoAccount?.getTokenBalanceUi(outputBank)
return balance && balance < 0 ? Math.abs(balance) : 0
}, [outputBank])
const loadingSwapDetails: boolean = useMemo(() => {
return (
!!(amountInAsDecimal.toNumber() || amountOutAsDecimal.toNumber()) &&
connected &&
typeof selectedRoute === 'undefined'
)
}, [amountInAsDecimal, amountOutAsDecimal, connected, selectedRoute])
const handleSwapOrLimit = useCallback(
(orderType: string) => {
setSwapOrLimit(orderType)
},
[outputBank, set, setSwapOrLimit],
)
const handleSetMargin = () => {
set((s) => {
@ -318,33 +117,26 @@ const SwapForm = () => {
setSavedSwapMargin(useMargin)
}, [useMargin])
const estSlippage = useMemo(() => {
const { group } = mangoStore.getState()
const amountIn = parseFloat(amountInFormValue) || 0
if (!group || !inputBank || amountIn <= 0) return 0
const value = amountIn * inputBank.uiPrice
const slippage = group.getPriceImpactByTokenIndex(
inputBank.tokenIndex,
value,
)
return slippage
}, [amountInFormValue, inputBank])
return (
<ContentBox
hidePadding
className="relative overflow-hidden border-x-0 md:border-l md:border-r-0 md:border-t-0 md:border-b-0"
className="relative overflow-hidden border-x-0 bg-th-bkg-1 md:border-l md:border-r-0 md:border-t-0 md:border-b-0"
>
<div>
<Transition
className="absolute top-0 right-0 z-10 h-full w-full bg-th-bkg-1 pb-0"
show={showConfirm}
enter="transition ease-in duration-300"
enterFrom="-translate-x-full"
enterTo="translate-x-0"
leave="transition ease-out duration-300"
leaveFrom="translate-x-0"
leaveTo="-translate-x-full"
>
<SwapReviewRouteInfo
onClose={() => setShowConfirm(false)}
amountIn={amountInAsDecimal}
slippage={slippage}
routes={routes}
selectedRoute={selectedRoute}
setSelectedRoute={setSelectedRoute}
/>
</Transition>
<EnterBottomExitBottom
className="thin-scroll absolute bottom-0 left-0 z-10 h-full w-full overflow-hidden bg-th-bkg-1 p-6 pb-0"
className="thin-scroll absolute bottom-0 left-0 z-10 h-full w-full overflow-auto bg-th-bkg-1 p-6 pb-0"
show={!!showTokenSelect}
>
<SwapFormTokenList
@ -364,175 +156,25 @@ const SwapForm = () => {
>
<SwapSettings onClose={() => setShowSettings(false)} />
</EnterBottomExitBottom>
<div className="relative p-6 pt-10">
<div className="absolute right-4 top-4">
<IconButton
className="text-th-fgd-3"
hideBg
onClick={() => setShowSettings(true)}
>
<Cog8ToothIcon className="h-5 w-5" />
</IconButton>
</div>
<div className="mb-2 flex items-end justify-between">
<p className="text-th-fgd-2 lg:text-base">{t('swap:pay')}</p>
{!isUnownedAccount ? (
<MaxSwapAmount
useMargin={useMargin}
setAmountIn={(v) => setAmountInFormValue(v, true)}
/>
) : null}
</div>
<div className="mb-3 grid grid-cols-2" id="swap-step-two">
<div className="col-span-1">
<TokenSelect
bank={
inputBank ||
group?.banksMapByName.get(INPUT_TOKEN_DEFAULT)?.[0]
}
showTokenList={setShowTokenSelect}
type="input"
<div className="relative p-6">
{isWhiteListed ? (
<div className="relative mb-6">
<TabUnderline
activeValue={swapOrLimit}
values={['swap', 'trade:trigger-order']}
onChange={(v) => handleSwapOrLimit(v)}
/>
</div>
<div className="relative col-span-1">
<NumberFormat
inputMode="decimal"
thousandSeparator=","
allowNegative={false}
isNumericString={true}
decimalScale={inputBank?.mintDecimals || 6}
name="amountIn"
id="amountIn"
className={NUMBER_FORMAT_CLASSNAMES}
placeholder="0.00"
value={amountInFormValue}
onValueChange={handleAmountInChange}
isAllowed={withValueLimit}
/>
<span className="absolute right-3 bottom-1.5 text-xxs text-th-fgd-4">
{inputBank
? formatCurrencyValue(
inputBank.uiPrice * Number(amountInFormValue),
)
: ''}
</span>
</div>
</div>
<div className="-mb-2 flex justify-center">
<button
className="rounded-full border border-th-bkg-4 p-1.5 text-th-fgd-3 focus-visible:border-th-fgd-4 md:hover:text-th-active"
onClick={() =>
handleSwitchTokens(amountInAsDecimal, amountOutAsDecimal)
}
>
<ArrowDownIcon
className="h-5 w-5"
style={
animateSwitchArrow % 2 == 0
? { transform: 'rotate(0deg)' }
: { transform: 'rotate(360deg)' }
}
/>
</button>
</div>
<div className="mb-2 flex items-end justify-between">
<p className="text-th-fgd-2 lg:text-base">{t('swap:receive')}</p>
{outputTokenBalanceBorrow ? (
<MaxAmountButton
className="mb-0.5 text-xs"
decimals={outputBank?.mintDecimals || 9}
label={t('repay')}
onClick={() =>
setBorrowAmountOut(
outputTokenBalanceBorrow.toFixed(
outputBank?.mintDecimals || 9,
),
)
}
value={outputTokenBalanceBorrow}
/>
) : null}
</div>
<div id="swap-step-three" className="mb-3 grid grid-cols-2">
<div className="col-span-1">
<TokenSelect
bank={
outputBank ||
group?.banksMapByName.get(OUTPUT_TOKEN_DEFAULT)?.[0]
}
showTokenList={setShowTokenSelect}
type="output"
/>
</div>
<div className="relative col-span-1">
{loadingSwapDetails ? (
<div className="flex h-[56px] w-full items-center justify-center rounded-l-none rounded-r-lg border border-th-input-border bg-th-bkg-2">
<Loading />
</div>
) : (
<>
<NumberFormat
inputMode="decimal"
thousandSeparator=","
allowNegative={false}
isNumericString={true}
decimalScale={outputBank?.mintDecimals || 6}
name="amountOut"
id="amountOut"
className={NUMBER_FORMAT_CLASSNAMES}
placeholder="0.00"
value={amountOutFormValue}
onValueChange={handleAmountOutChange}
/>
<span className="absolute right-3 bottom-1.5 text-xxs text-th-fgd-4">
{outputBank
? formatCurrencyValue(
outputBank.uiPrice * Number(amountOutFormValue),
)
: ''}
</span>
</>
)}
</div>
</div>
{swapFormSizeUi === 'slider' ? (
<SwapSlider
useMargin={useMargin}
amount={amountInAsDecimal.toNumber()}
onChange={setAmountFromSlider}
step={1 / 10 ** (inputBank?.mintDecimals || 6)}
/>
) : null}
{swapOrLimit === 'swap' ? (
<MarketSwapForm setShowTokenSelect={setShowTokenSelect} />
) : (
<PercentageSelectButtons
amountIn={amountInAsDecimal.toString()}
setAmountIn={setAmountFromSlider}
useMargin={useMargin}
<LimitSwapForm
showTokenSelect={showTokenSelect}
setShowTokenSelect={setShowTokenSelect}
/>
)}
{ipAllowed ? (
<SwapFormSubmitButton
loadingSwapDetails={loadingSwapDetails}
useMargin={useMargin}
selectedRoute={selectedRoute}
setShowConfirm={setShowConfirm}
amountIn={amountInAsDecimal}
inputSymbol={inputBank?.name}
amountOut={
selectedRoute ? amountOutAsDecimal.toNumber() : undefined
}
/>
) : (
<Button
disabled
className="mt-6 mb-4 w-full leading-tight"
size="large"
>
{t('country-not-allowed', {
country: ipCountry ? `(${ipCountry})` : '',
})}
</Button>
)}
{group && inputBank ? (
{inputBank ? (
<TokenVaultWarnings bank={inputBank} type="swap" />
) : null}
{inputBank &&
@ -563,28 +205,47 @@ const SwapForm = () => {
<div id="swap-step-four">
<HealthImpact maintProjectedHealth={maintProjectedHealth} />
</div>
<div className="flex items-center justify-between">
<Tooltip content={t('swap:tooltip-margin')}>
<p className="tooltip-underline text-sm text-th-fgd-3">
{t('swap:margin')}
</p>
</Tooltip>
<Switch
className="text-th-fgd-3"
checked={useMargin}
onChange={handleSetMargin}
small
/>
</div>
<div className="flex items-center justify-between">
<p className="text-sm text-th-fgd-3">{t('swap:max-slippage')}</p>
<LinkButton
className="text-right font-mono text-sm font-normal text-th-fgd-2 underline underline-offset-2 md:hover:no-underline"
onClick={() => setShowSettings(true)}
>
{slippage}%
</LinkButton>
</div>
{swapOrLimit === 'swap' ? (
<>
<div className="flex items-center justify-between">
<Tooltip content={t('swap:tooltip-margin')}>
<p className="tooltip-underline text-sm text-th-fgd-3">
{t('swap:margin')}
</p>
</Tooltip>
<Switch
className="text-th-fgd-3"
checked={useMargin}
onChange={handleSetMargin}
small
/>
</div>
<div className="flex items-center justify-between">
<p className="text-sm text-th-fgd-3">
{t('swap:max-slippage')}
</p>
<LinkButton
className="flex items-center text-right font-mono text-sm font-normal text-th-fgd-2"
onClick={() => setShowSettings(true)}
>
<span className="mr-1.5">{slippage}%</span>
<PencilIcon className="h-4 w-4" />
</LinkButton>
</div>
</>
) : null}
{estSlippage ? (
<>
<div className="flex items-center justify-between">
<p className="text-sm text-th-fgd-3">
{t('trade:est-slippage')}
</p>
<span className="font-mono text-th-fgd-2">
{estSlippage.toFixed(2)}%
</span>
</div>
</>
) : null}
</div>
</div>
</div>
@ -593,109 +254,3 @@ const SwapForm = () => {
}
export default SwapForm
const SwapFormSubmitButton = ({
amountIn,
amountOut,
inputSymbol,
loadingSwapDetails,
selectedRoute,
setShowConfirm,
useMargin,
}: {
amountIn: Decimal
amountOut: number | undefined
inputSymbol: string | undefined
loadingSwapDetails: boolean
selectedRoute: RouteInfo | undefined | null
setShowConfirm: (x: boolean) => void
useMargin: boolean
}) => {
const { t } = useTranslation('common')
const { connected, connect } = useWallet()
const { amount: tokenMax, amountWithBorrow } = useTokenMax(useMargin)
const { usedTokens, totalTokens } = useMangoAccountAccounts()
const { inputBank, outputBank } = mangoStore((s) => s.swap)
const tokenPositionsFull = useMemo(() => {
if (!inputBank || !outputBank || !usedTokens.length || !totalTokens.length)
return false
const hasInputTokenPosition = usedTokens.find(
(token) => token.tokenIndex === inputBank.tokenIndex,
)
const hasOutputTokenPosition = usedTokens.find(
(token) => token.tokenIndex === outputBank.tokenIndex,
)
if (
(hasInputTokenPosition && hasOutputTokenPosition) ||
totalTokens.length - usedTokens.length >= 2
) {
return false
} else return true
}, [inputBank, outputBank, usedTokens, totalTokens])
const showInsufficientBalance = useMargin
? amountWithBorrow.lt(amountIn)
: tokenMax.lt(amountIn)
const disabled =
connected &&
(!amountIn.toNumber() ||
showInsufficientBalance ||
!amountOut ||
!selectedRoute ||
tokenPositionsFull)
const onClick = connected ? () => setShowConfirm(true) : connect
return (
<>
<Button
onClick={onClick}
className="mt-6 mb-4 flex w-full items-center justify-center text-base"
disabled={disabled}
size="large"
>
{connected ? (
showInsufficientBalance ? (
<div className="flex items-center">
<ExclamationCircleIcon className="mr-2 h-5 w-5 flex-shrink-0" />
{t('swap:insufficient-balance', {
symbol: inputSymbol,
})}
</div>
) : loadingSwapDetails ? (
<Loading />
) : (
<span>{t('swap:review-swap')}</span>
)
) : (
<div className="flex items-center">
<LinkIcon className="mr-2 h-5 w-5" />
{t('connect')}
</div>
)}
</Button>
{tokenPositionsFull ? (
<div className="pb-4">
<InlineNotification
type="error"
desc={
<>
{t('error-token-positions-full')}{' '}
<Link href="/settings" shallow>
{t('manage')}
</Link>
</>
}
/>
</div>
) : null}
{selectedRoute === null && amountIn.gt(0) ? (
<div className="mb-4">
<InlineNotification type="error" desc={t('swap:no-swap-found')} />
</div>
) : null}
</>
)
}

View File

@ -209,9 +209,9 @@ const SwapFormTokenList = ({
<>
<p className="mb-3">
{type === 'input'
? t('swap:pay')
? t('swap:you-sell')
: type === 'output'
? t('swap:receive')
? t('swap:you-buy')
: ''}
</p>
<IconButton

View File

@ -1,26 +1,34 @@
import { useMemo, useState } from 'react'
import TabButtons from '@components/shared/TabButtons'
import SwapTradeBalances from '../shared/BalancesTable'
import mangoStore from '@store/mangoStore'
import SwapHistoryTable from './SwapHistoryTable'
import useMangoAccount from 'hooks/useMangoAccount'
import ManualRefresh from '@components/shared/ManualRefresh'
import { useViewport } from 'hooks/useViewport'
import { breakpoints } from 'utils/theme'
import SwapOrders from './SwapOrders'
import { useIsWhiteListed } from 'hooks/useIsWhiteListed'
const SwapInfoTabs = () => {
const [selectedTab, setSelectedTab] = useState('balances')
const openOrders = mangoStore((s) => s.mangoAccount.openOrders)
const { mangoAccount } = useMangoAccount()
const { width } = useViewport()
const { data: isWhiteListed } = useIsWhiteListed()
const isMobile = width ? width < breakpoints.lg : false
const tabsWithCount: [string, number][] = useMemo(() => {
return [
const tabs: [string, number][] = [
['balances', 0],
['swap:swap-history', 0],
]
}, [openOrders, mangoAccount])
if (isWhiteListed) {
const stopOrdersCount =
mangoAccount?.tokenConditionalSwaps.filter((tcs) => tcs.hasData)
?.length || 0
tabs.splice(1, 0, ['trade:trigger-orders', stopOrdersCount])
}
return tabs
}, [isWhiteListed, mangoAccount])
return (
<div className="hide-scroll h-full overflow-y-scroll">
@ -38,6 +46,7 @@ const SwapInfoTabs = () => {
/>
</div>
{selectedTab === 'balances' ? <SwapTradeBalances /> : null}
{selectedTab === 'trade:trigger-orders' ? <SwapOrders /> : null}
{selectedTab === 'swap:swap-history' ? <SwapHistoryTable /> : null}
</div>
)

View File

@ -0,0 +1,499 @@
import { IconButton, LinkButton } from '@components/shared/Button'
import ConnectEmptyState from '@components/shared/ConnectEmptyState'
import {
SortableColumnHeader,
Table,
Td,
Th,
TrBody,
TrHead,
} from '@components/shared/TableElements'
import {
ChevronDownIcon,
NoSymbolIcon,
TrashIcon,
} from '@heroicons/react/20/solid'
import { BN } from '@project-serum/anchor'
import { useWallet } from '@solana/wallet-adapter-react'
import mangoStore from '@store/mangoStore'
import useMangoAccount from 'hooks/useMangoAccount'
import useMangoGroup from 'hooks/useMangoGroup'
import { useSortableData } from 'hooks/useSortableData'
import { useViewport } from 'hooks/useViewport'
import { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { notify } from 'utils/notifications'
import { floorToDecimal } from 'utils/numbers'
import { breakpoints } from 'utils/theme'
import * as sentry from '@sentry/nextjs'
import { isMangoError } from 'types'
import Loading from '@components/shared/Loading'
import SideBadge from '@components/shared/SideBadge'
import { Disclosure, Transition } from '@headlessui/react'
import SheenLoader from '@components/shared/SheenLoader'
const SwapOrders = () => {
const { t } = useTranslation(['common', 'swap', 'trade'])
const { width } = useViewport()
const showTableView = width ? width > breakpoints.md : false
const { mangoAccount, mangoAccountAddress } = useMangoAccount()
const { group } = useMangoGroup()
const { connected } = useWallet()
const [cancelId, setCancelId] = useState('')
const orders = useMemo(() => {
if (!mangoAccount) return []
return mangoAccount.tokenConditionalSwaps.filter((tcs) => tcs.hasData)
}, [mangoAccount])
const formattedTableData = useCallback(() => {
if (!group) return []
const formatted = []
for (const order of orders) {
const buyBank = group.getFirstBankByTokenIndex(order.buyTokenIndex)
const sellBank = group.getFirstBankByTokenIndex(order.sellTokenIndex)
const pair = `${sellBank.name}/${buyBank.name}`
const maxBuy = floorToDecimal(
order.getMaxBuyUi(group),
buyBank.mintDecimals,
).toNumber()
const maxSell = floorToDecimal(
order.getMaxSellUi(group),
sellBank.mintDecimals,
).toNumber()
let size
let side
if (maxBuy === 0 || maxBuy > maxSell) {
size = maxSell
side = 'sell'
} else {
size = maxBuy
side = 'buy'
}
const triggerPrice = order.getThresholdPriceUi(group)
const pricePremium = order.getPricePremium()
const filled = order.getSoldUi(group)
const currentPrice = order.getCurrentPairPriceUi(group)
const data = {
...order,
buyBank,
currentPrice,
sellBank,
pair,
side,
size,
filled,
triggerPrice,
fee: pricePremium,
}
formatted.push(data)
}
return formatted
}, [group, orders])
const {
items: tableData,
requestSort,
sortConfig,
} = useSortableData(formattedTableData())
const handleCancel = async (id: BN) => {
try {
const client = mangoStore.getState().client
const group = mangoStore.getState().group
const actions = mangoStore.getState().actions
const mangoAccount = mangoStore.getState().mangoAccount.current
if (!mangoAccount || !group) return
setCancelId(id.toString())
try {
const { signature: tx, slot } = await client.tokenConditionalSwapCancel(
group,
mangoAccount,
id,
)
notify({
title: 'Transaction confirmed',
type: 'success',
txid: tx,
noSound: true,
})
actions.fetchGroup()
await actions.reloadMangoAccount(slot)
} catch (e) {
console.error('failed to cancel swap order', e)
sentry.captureException(e)
if (isMangoError(e)) {
notify({
title: 'Transaction failed',
description: e.message,
txid: e?.txid,
type: 'error',
})
}
}
} catch (e) {
console.error('failed to cancel trigger order', e)
} finally {
setCancelId('')
}
}
const handleCancelAll = async () => {
try {
const client = mangoStore.getState().client
const group = mangoStore.getState().group
const actions = mangoStore.getState().actions
const mangoAccount = mangoStore.getState().mangoAccount.current
if (!mangoAccount || !group) return
setCancelId('all')
try {
const { signature: tx, slot } =
await client.tokenConditionalSwapCancelAll(group, mangoAccount)
notify({
title: 'Transaction confirmed',
type: 'success',
txid: tx,
noSound: true,
})
actions.fetchGroup()
await actions.reloadMangoAccount(slot)
} catch (e) {
console.error('failed to cancel trigger orders', e)
sentry.captureException(e)
if (isMangoError(e)) {
notify({
title: 'Transaction failed',
description: e.message,
txid: e?.txid,
type: 'error',
})
}
}
} catch (e) {
console.error('failed to cancel swap order', e)
} finally {
setCancelId('')
}
}
return orders.length ? (
showTableView ? (
<Table>
<thead>
<TrHead>
<Th className="text-left">
<SortableColumnHeader
sortKey="pair"
sort={() => requestSort('pair')}
sortConfig={sortConfig}
title={t('swap:pair')}
/>
</Th>
<Th>
<div className="flex justify-end">
<SortableColumnHeader
sortKey="side"
sort={() => requestSort('side')}
sortConfig={sortConfig}
title={t('trade:side')}
/>
</div>
</Th>
<Th>
<div className="flex justify-end">
<SortableColumnHeader
sortKey="size"
sort={() => requestSort('size')}
sortConfig={sortConfig}
title={t('trade:size')}
/>
</div>
</Th>
<Th>
<div className="flex justify-end">
<SortableColumnHeader
sortKey="filled"
sort={() => requestSort('filled')}
sortConfig={sortConfig}
title={t('trade:filled')}
/>
</div>
</Th>
<Th>
<div className="flex justify-end">
<SortableColumnHeader
sortKey="currentPrice"
sort={() => requestSort('currentPrice')}
sortConfig={sortConfig}
title={t('trade:current-price')}
/>
</div>
</Th>
<Th>
<div className="flex justify-end">
<SortableColumnHeader
sortKey="triggerPrice"
sort={() => requestSort('triggerPrice')}
sortConfig={sortConfig}
title={t('trade:trigger-price')}
/>
</div>
</Th>
<Th>
<div className="flex justify-end">
<SortableColumnHeader
sortKey="fee"
sort={() => requestSort('fee')}
sortConfig={sortConfig}
title={t('trade:est-slippage')}
/>
</div>
</Th>
<Th>
<div className="flex justify-end">
<LinkButton onClick={handleCancelAll}>
{t('trade:cancel-all')}
</LinkButton>
</div>
</Th>
</TrHead>
</thead>
<tbody>
{tableData.map((data, i) => {
const {
buyBank,
currentPrice,
fee,
pair,
sellBank,
side,
size,
filled,
triggerPrice,
} = data
const bank = side === 'buy' ? buyBank : sellBank
return (
<TrBody key={i} className="text-sm">
<Td>{pair}</Td>
<Td>
<div className="flex justify-end">
<SideBadge side={side} />
</div>
</Td>
<Td>
<p className="text-right">
{size}
<span className="text-th-fgd-3 font-body">
{' '}
{bank.name}
</span>
</p>
</Td>
<Td>
<p className="text-right">
{filled}/{size}
<span className="text-th-fgd-3 font-body">
{' '}
{bank.name}
</span>
</p>
</Td>
<Td>
<p className="text-right">
{currentPrice}
<span className="text-th-fgd-3 font-body">
{' '}
{buyBank.name}
</span>
</p>
</Td>
<Td>
<p className="text-right">
{triggerPrice}
<span className="text-th-fgd-3 font-body">
{' '}
{side === 'buy' ? sellBank.name : buyBank.name}
</span>
</p>
</Td>
<Td>
<p className="text-right">{fee.toFixed(2)}%</p>
</Td>
<Td className="flex justify-end">
<IconButton
disabled={
cancelId === data.id.toString() || cancelId === 'all'
}
onClick={() => handleCancel(data.id)}
size="small"
>
{cancelId === data.id.toString() || cancelId === 'all' ? (
<Loading />
) : (
<TrashIcon className="h-4 w-4" />
)}
</IconButton>
</Td>
</TrBody>
)
})}
</tbody>
</Table>
) : (
<div className="border-b border-th-bkg-3">
{tableData.map((data, i) => {
const {
buyBank,
currentPrice,
fee,
pair,
sellBank,
side,
size,
filled,
triggerPrice,
} = data
const bank = side === 'buy' ? buyBank : sellBank
return (
<Disclosure key={i}>
{({ open }) => (
<>
<Disclosure.Button
className={`w-full border-t border-th-bkg-3 p-4 text-left focus:outline-none ${
i === 0 ? 'border-t-0' : ''
}`}
>
<div className="flex items-center justify-between">
<div>
<span className="mr-1 whitespace-nowrap">{pair}</span>
<SideBadge side={side} />
<p className="font-mono text-th-fgd-2">
{size}
<span className="text-th-fgd-3 font-body">
{' '}
{bank.name}
</span>
<span className="text-th-fgd-3 font-body">
{' at '}
</span>
{triggerPrice}
<span className="text-th-fgd-3 font-body">
{' '}
{side === 'buy' ? sellBank.name : buyBank.name}
</span>
</p>
</div>
<ChevronDownIcon
className={`${
open ? 'rotate-180' : 'rotate-360'
} h-6 w-6 flex-shrink-0 text-th-fgd-3`}
/>
</div>
</Disclosure.Button>
<Transition
enter="transition ease-in duration-200"
enterFrom="opacity-0"
enterTo="opacity-100"
>
<Disclosure.Panel>
<div className="mx-4 grid grid-cols-2 gap-4 border-t border-th-bkg-3 pt-4 pb-4">
<div className="col-span-1">
<p className="text-xs text-th-fgd-3">
{t('trade:size')}
</p>
<p className="font-mono text-th-fgd-1">
{size}
<span className="text-th-fgd-3 font-body">
{' '}
{bank.name}
</span>
</p>
</div>
<div className="col-span-1">
<p className="text-xs text-th-fgd-3">
{t('trade:filled')}
</p>
<p className="font-mono text-th-fgd-1">
{filled}/{size}
<span className="text-th-fgd-3 font-body">
{' '}
{bank.name}
</span>
</p>
</div>
<div className="col-span-1">
<p className="text-xs text-th-fgd-3">
{t('trade:current-price')}
</p>
<p className="font-mono text-th-fgd-1">
{currentPrice}
<span className="text-th-fgd-3 font-body">
{' '}
{buyBank.name}
</span>
</p>
</div>
<div className="col-span-1">
<p className="text-xs text-th-fgd-3">
{t('trade:trigger-price')}
</p>
<p className="font-mono text-th-fgd-1">
{triggerPrice}
<span className="text-th-fgd-3 font-body">
{' '}
{side === 'buy' ? sellBank.name : buyBank.name}
</span>
</p>
</div>
<div className="col-span-1">
<p className="text-xs text-th-fgd-3">
{t('trade:est-slippage')}
</p>
<p className="font-mono text-th-fgd-1">
{fee.toFixed(2)}%
</p>
</div>
<div className="col-span-1">
<p className="text-xs text-th-fgd-3">{t('cancel')}</p>
<LinkButton onClick={() => handleCancel(data.id)}>
{cancelId === data.id.toString() ? (
<SheenLoader className="mt-1">
<div className="h-3.5 w-20 bg-th-bkg-2" />
</SheenLoader>
) : (
t('trade:cancel-order')
)}
</LinkButton>
</div>
</div>
</Disclosure.Panel>
</Transition>
</>
)}
</Disclosure>
)
})}
</div>
)
) : mangoAccountAddress || connected ? (
<div className="flex flex-col items-center p-8">
<NoSymbolIcon className="mb-2 h-6 w-6 text-th-fgd-4" />
<p>{t('trade:no-orders')}</p>
</div>
) : (
<div className="p-8">
<ConnectEmptyState text={t('connect-orders')} />
</div>
)
}
export default SwapOrders

View File

@ -1,4 +1,4 @@
import {
import React, {
MouseEventHandler,
useCallback,
useEffect,
@ -52,6 +52,8 @@ import FavoriteSwapButton from './FavoriteSwapButton'
dayjs.extend(relativeTime)
const set = mangoStore.getState().set
const CustomizedLabel = ({
chartData,
x,
@ -176,14 +178,12 @@ const SwapHistoryArrows = (props: ExtendedReferenceDotProps) => {
const SwapTokenChart = () => {
const { t } = useTranslation('common')
const inputBank = mangoStore((s) => s.swap.inputBank)
const outputBank = mangoStore((s) => s.swap.outputBank)
const { inputBank, outputBank, flipPrices } = mangoStore((s) => s.swap)
const { inputCoingeckoId, outputCoingeckoId } = useJupiterSwapData()
const [baseTokenId, setBaseTokenId] = useState(inputCoingeckoId)
const [quoteTokenId, setQuoteTokenId] = useState(outputCoingeckoId)
const [mouseData, setMouseData] = useState<ChartDataItem>()
const [daysToShow, setDaysToShow] = useState('1')
const [flipPrices, setFlipPrices] = useState(false)
const { theme } = useThemeWrapper()
const [animationSettings] = useLocalStorageState(
ANIMATION_SETTINGS_KEY,
@ -198,6 +198,20 @@ const SwapTokenChart = () => {
string | number | undefined
>(undefined)
const [inputBankName, outputBankName] = useMemo(() => {
if (!inputBank || !outputBank) return ['', '']
return [inputBank.name, outputBank.name]
}, [inputBank, outputBank])
const swapMarketName = useMemo(() => {
if (!inputBankName || !outputBankName) return ''
const inputSymbol = formatTokenSymbol(inputBankName)
const outputSymbol = formatTokenSymbol(outputBankName)
return flipPrices
? `${outputSymbol}/${inputSymbol}`
: `${inputSymbol}/${outputSymbol}`
}, [flipPrices, inputBankName, outputBankName])
const handleSwapMouseEnter = useCallback(
(
swap: SwapHistoryItem | undefined,
@ -217,19 +231,6 @@ const SwapTokenChart = () => {
setSwapTooltipData(null)
}, [setSwapTooltipData])
const swapMarketName = useMemo(() => {
if (!inputBank || !outputBank) return ''
const inputSymbol = formatTokenSymbol(inputBank.name)
const outputSymbol = formatTokenSymbol(outputBank.name)
return ['usd-coin', 'tether'].includes(inputCoingeckoId || '')
? !flipPrices
? `${outputSymbol}/${inputSymbol}`
: `${inputSymbol}/${outputSymbol}`
: !flipPrices
? `${inputSymbol}/${outputSymbol}`
: `${outputSymbol}/${inputSymbol}`
}, [flipPrices, inputBank, inputCoingeckoId, outputBank])
const renderTooltipContent = useCallback(
(swap: SwapHistoryItem) => {
const {
@ -326,47 +327,40 @@ const SwapTokenChart = () => {
)
const {
data: coingeckoDataQuery,
data: coingeckoData,
isLoading,
isFetching,
} = useQuery(
['swap-chart-data', baseTokenId, quoteTokenId, daysToShow],
() => fetchChartData(baseTokenId, quoteTokenId, daysToShow),
['swap-chart-data', baseTokenId, quoteTokenId, daysToShow, flipPrices],
() =>
fetchChartData(
baseTokenId,
inputBank,
quoteTokenId,
outputBank,
daysToShow,
flipPrices,
),
{
cacheTime: 1000 * 60 * 15,
staleTime: 1000 * 60 * 1,
enabled: !!baseTokenId && !!quoteTokenId,
enabled: !!(baseTokenId && quoteTokenId),
refetchOnWindowFocus: false,
},
)
const coingeckoData = useMemo(() => {
if (!coingeckoDataQuery || !coingeckoDataQuery.length) return []
if (!flipPrices) {
return coingeckoDataQuery
} else {
return coingeckoDataQuery.map((d: ChartDataItem) => {
const price =
d.inputTokenPrice / d.outputTokenPrice === d.price
? d.outputTokenPrice / d.inputTokenPrice
: d.inputTokenPrice / d.outputTokenPrice
return { ...d, price: price }
})
}
}, [flipPrices, coingeckoDataQuery])
const chartSwapTimes = useMemo(() => {
if (
loadSwapHistory ||
!swapHistory ||
!swapHistory.length ||
!inputBank ||
!outputBank
!inputBankName ||
!outputBankName
)
return []
const chartSymbols = [
inputBank.name === 'ETH (Portal)' ? 'ETH' : inputBank.name,
outputBank.name === 'ETH (Portal)' ? 'ETH' : outputBank.name,
inputBankName === 'ETH (Portal)' ? 'ETH' : inputBankName,
outputBankName === 'ETH (Portal)' ? 'ETH' : outputBankName,
]
return swapHistory
.filter(
@ -375,10 +369,11 @@ const SwapTokenChart = () => {
chartSymbols.includes(swap.swap_out_symbol),
)
.map((val) => dayjs(val.block_datetime).unix() * 1000)
}, [swapHistory, loadSwapHistory, inputBank, outputBank])
}, [swapHistory, loadSwapHistory, inputBankName, outputBankName])
const swapHistoryPoints = useMemo(() => {
if (!coingeckoData.length || !chartSwapTimes.length) return []
if (!coingeckoData || !coingeckoData.length || !chartSwapTimes.length)
return []
return chartSwapTimes.map((x) => {
const makeChartDataItem = { inputTokenPrice: 1, outputTokenPrice: 1 }
const index = coingeckoData.findIndex((d) => d.time > x) // find index of data point with x value greater than highlight x
@ -430,20 +425,15 @@ const SwapTokenChart = () => {
useEffect(() => {
if (!inputCoingeckoId || !outputCoingeckoId) return
if (['usd-coin', 'tether'].includes(outputCoingeckoId)) {
setBaseTokenId(inputCoingeckoId)
setQuoteTokenId(outputCoingeckoId)
} else {
setBaseTokenId(outputCoingeckoId)
setQuoteTokenId(inputCoingeckoId)
}
setBaseTokenId(inputCoingeckoId)
setQuoteTokenId(outputCoingeckoId)
}, [inputCoingeckoId, outputCoingeckoId])
const calculateChartChange = useCallback(() => {
if (!chartData?.length) return 0
if (mouseData) {
const index = chartData.findIndex((d) => d.time === mouseData.time)
if (index === -1) return 0
return (
((chartData[index]['price'] - chartData[0]['price']) /
chartData[0]['price']) *
@ -481,12 +471,16 @@ const SwapTokenChart = () => {
) : null}
<div className="flex items-start justify-between">
<div>
{inputBank && outputBank ? (
{inputBankName && outputBankName ? (
<div className="mb-0.5 flex items-center">
<p className="text-base text-th-fgd-3">{swapMarketName}</p>
<IconButton
className="px-2 text-th-fgd-3"
onClick={() => setFlipPrices(!flipPrices)}
onClick={() =>
set((state) => {
state.swap.flipPrices = !flipPrices
})
}
hideBg
>
<ArrowsRightLeftIcon className="h-5 w-5" />
@ -548,7 +542,7 @@ const SwapTokenChart = () => {
)}
</div>
</div>
<div className="mt-2 h-40 w-auto md:h-72">
<div className="mt-2 h-40 w-auto md:h-96">
<div className="absolute top-[2px] right-0 -mb-2 flex items-center justify-end space-x-4">
<FavoriteSwapButton
inputToken={inputBank!.name}
@ -678,4 +672,4 @@ const SwapTokenChart = () => {
)
}
export default SwapTokenChart
export default React.memo(SwapTokenChart)

View File

@ -19,7 +19,7 @@ const TokenSelect = ({ bank, showTokenList, type }: TokenSelectProps) => {
return (
<button
onClick={() => showTokenList(type)}
className="flex h-full w-full items-center rounded-lg rounded-r-none border border-r-0 border-th-input-border bg-th-input-bkg py-2 px-3 text-th-fgd-2 focus-visible:bg-th-bkg-2 md:hover:cursor-pointer md:hover:bg-th-bkg-2 md:hover:text-th-fgd-1"
className="flex h-[56px] w-full items-center rounded-lg rounded-r-none bg-th-input-bkg py-2 px-3 text-th-fgd-2 focus-visible:bg-th-bkg-3 md:hover:cursor-pointer md:hover:bg-th-bkg-1 md:hover:text-th-fgd-1"
>
<div className="mr-2.5 flex min-w-[24px] items-center">
<TokenLogo bank={bank} />

View File

@ -22,7 +22,7 @@
},
"dependencies": {
"@blockworks-foundation/mango-feeds": "0.1.7",
"@blockworks-foundation/mango-v4": "^0.19.2",
"@blockworks-foundation/mango-v4": "^0.19.3",
"@blockworks-foundation/mango-v4-settings": "0.2.6",
"@headlessui/react": "1.6.6",
"@heroicons/react": "2.0.10",

View File

@ -1,9 +1,11 @@
{
"confirm-swap": "Confirm Swap",
"connect-swap": "Connect to view your swap history",
"deposit-funds": "Deposit Funds",
"disabled": "Disabled",
"enabled": "Enabled",
"est-liq-price": "Est. Liq Price",
"est-received": "Est. Received",
"fees-paid-to": "Fees Paid to {{route}}",
"health-impact": "Health Impact",
"hide-fees": "Hide Fees",
@ -16,14 +18,16 @@
"max-slippage": "Max Slippage",
"maximum-cost": "Maximum Cost",
"minimum-received": "Minimum Received",
"no-borrow": "No borrow to repay",
"no-history": "No swap history",
"no-swap-found": "No swap found",
"output-reduce-only-warning": "{{symbol}} is in reduce only mode. You can swap to close borrows only",
"paid": "Paid",
"pay": "You Pay",
"pair": "Pair",
"place-limit-order": "Place Order",
"preset": "Preset",
"price-impact": "Price Impact",
"rate": "Rate",
"receive": "You Receive",
"received": "Received",
"review-swap": "Review Swap",
"route-info": "Route Info",
@ -42,5 +46,7 @@
"tooltip-favorite-swap-add": "Add pair to favorites",
"tooltip-favorite-swap-remove": "Remove pair from favorites",
"use-margin": "Allow Margin",
"no-swap-found": "No swap found"
"warning-no-collateral": "You have no free collateral",
"you-buy": "You're buying",
"you-sell": "You're selling"
}

View File

@ -2,11 +2,14 @@
"24h-volume": "24h Volume",
"activate-volume-alert": "Activate Volume Alert",
"amount": "Amount",
"avg-entry-price": "Avg. Entry Price",
"average-funding": "Average {{interval}} Funding",
"average-price-of": "at an average price of",
"base": "Base",
"book": "Book",
"buys": "Buys",
"cancel-all": "Cancel All",
"cancel-order": "Cancel Order",
"cancel-order-error": "Failed to cancel order",
"close-confirm": "Market close your {{config_name}} position",
"close-position": "Close Position",
@ -19,8 +22,9 @@
"depth": "Depth",
"edit-order": "Edit Order",
"est-liq-price": "Est. Liq. Price",
"avg-entry-price": "Avg. Entry Price",
"est-slippage": "Est. Slippage",
"falls-to": "falls to",
"filled": "Filled",
"for": "for",
"funding-limits": "Funding Limits",
"funding-rate": "1h Avg Funding Rate",
@ -72,7 +76,10 @@
"realized-pnl": "Realized PnL",
"reduce": "Reduce",
"reduce-only": "Reduce Only",
"repay-borrow-order-desc": "Repay {{amount}} {{symbol}} if the oracle price reaches {{triggerPrice}} {{priceUnit}}",
"repay-borrow-deposit-order-desc": "Repay {{borrowAmount}} and buy {{depositAmount}} {{symbol}} if the oracle price reaches {{triggerPrice}} {{priceUnit}}",
"return-on-equity": "Return on Equity",
"rises-to": "rises to",
"sells": "Sells",
"settle-funds": "Settle Funds",
"settle-funds-error": "Failed to settle funds",
@ -83,6 +90,10 @@
"size": "Size",
"spread": "Spread",
"stable-price": "Stable Price",
"stop-limit": "Stop Limit",
"stop-loss": "Stop Loss",
"stop-market": "Stop Market",
"take-profit": "Take Profit",
"taker": "Taker",
"taker-fee": "Taker Fee",
"tick-size": "Tick Size",
@ -99,6 +110,10 @@
"total-pnl": "Total PnL",
"trade-sounds-tooltip": "Play a sound alert for every new trade",
"trades": "Trades",
"trigger-price": "Trigger Price",
"trigger-order": "Trigger Order",
"trigger-order-desc": "{{amount}} {{symbol}} if the oracle price {{orderType}} {{triggerPrice}} {{priceUnit}}",
"trigger-orders": "Trigger Orders",
"tweet-position": "Tweet",
"unrealized-pnl": "Unrealized PnL",
"unsettled": "Unsettled",

View File

@ -1,9 +1,11 @@
{
"confirm-swap": "Confirm Swap",
"connect-swap": "Connect to view your swap history",
"deposit-funds": "Deposit Funds",
"disabled": "Disabled",
"enabled": "Enabled",
"est-liq-price": "Est. Liq Price",
"est-received": "Est. Received",
"fees-paid-to": "Fees Paid to {{route}}",
"health-impact": "Health Impact",
"hide-fees": "Hide Fees",
@ -16,14 +18,16 @@
"max-slippage": "Max Slippage",
"maximum-cost": "Maximum Cost",
"minimum-received": "Minimum Received",
"no-borrow": "No borrow to repay",
"no-history": "No swap history",
"no-swap-found": "No swap found",
"output-reduce-only-warning": "{{symbol}} is in reduce only mode. You can swap to close borrows only",
"paid": "Paid",
"pay": "You Pay",
"pair": "Pair",
"place-limit-order": "Place Order",
"preset": "Preset",
"price-impact": "Price Impact",
"rate": "Rate",
"receive": "You Receive",
"received": "Received",
"review-swap": "Review Swap",
"route-info": "Route Info",
@ -40,5 +44,7 @@
"tooltip-margin": "When margin is enabled you can add leverage to your swaps. Borrows are opened automatically if a swap exceeds your balance.",
"tooltip-max-slippage": "If price slips beyond your maximum slippage your swap will not be executed",
"use-margin": "Allow Margin",
"no-swap-found": "No swap found"
"warning-no-collateral": "You have no free collateral",
"you-buy": "You're buying",
"you-sell": "You're selling"
}

View File

@ -2,11 +2,14 @@
"24h-volume": "24h Volume",
"activate-volume-alert": "Activate Volume Alert",
"amount": "Amount",
"avg-entry-price": "Avg. Entry Price",
"average-funding": "Average {{interval}} Funding",
"average-price-of": "at an average price of",
"base": "Base",
"book": "Book",
"buys": "Buys",
"cancel-all": "Cancel All",
"cancel-order": "Cancel Order",
"cancel-order-error": "Failed to cancel order",
"close-confirm": "Market close your {{config_name}} position",
"close-position": "Close Position",
@ -19,8 +22,9 @@
"depth": "Depth",
"edit-order": "Edit Order",
"est-liq-price": "Est. Liq. Price",
"avg-entry-price": "Avg. Entry Price",
"est-slippage": "Est. Slippage",
"falls-to": "falls to",
"filled": "Filled",
"for": "for",
"funding-limits": "Funding Limits",
"funding-rate": "1h Avg Funding Rate",
@ -72,7 +76,10 @@
"realized-pnl": "Realized PnL",
"reduce": "Reduce",
"reduce-only": "Reduce Only",
"repay-borrow-order-desc": "Repay {{amount}} {{symbol}} if the oracle price reaches {{triggerPrice}} {{priceUnit}}",
"repay-borrow-deposit-order-desc": "Repay {{borrowAmount}} and buy {{depositAmount}} {{symbol}} if the oracle price reaches {{triggerPrice}} {{priceUnit}}",
"return-on-equity": "Return on Equity",
"rises-to": "rises to",
"sells": "Sells",
"settle-funds": "Settle Funds",
"settle-funds-error": "Failed to settle funds",
@ -83,6 +90,10 @@
"size": "Size",
"spread": "Spread",
"stable-price": "Stable Price",
"stop-limit": "Stop Limit",
"stop-loss": "Stop Loss",
"stop-market": "Stop Market",
"take-profit": "Take Profit",
"taker": "Taker",
"taker-fee": "Taker Fee",
"tick-size": "Tick Size",
@ -99,6 +110,10 @@
"total-pnl": "Total PnL",
"trade-sounds-tooltip": "Play a sound alert for every new trade",
"trades": "Trades",
"trigger-price": "Trigger Price",
"trigger-order": "Trigger Order",
"trigger-order-desc": "{{amount}} {{symbol}} if the oracle price {{orderType}} {{triggerPrice}} {{priceUnit}}",
"trigger-orders": "Trigger Orders",
"tweet-position": "Tweet",
"unrealized-pnl": "Unrealized PnL",
"unsettled": "Unsettled",

View File

@ -1,9 +1,11 @@
{
"confirm-swap": "Confirm Swap",
"connect-swap": "Connect to view your swap history",
"deposit-funds": "Deposit Funds",
"disabled": "Disabled",
"enabled": "Enabled",
"est-liq-price": "Est. Liq Price",
"est-received": "Est. Received",
"fees-paid-to": "Fees Paid to {{route}}",
"health-impact": "Health Impact",
"hide-fees": "Hide Fees",
@ -16,14 +18,16 @@
"max-slippage": "Max Slippage",
"maximum-cost": "Maximum Cost",
"minimum-received": "Minimum Received",
"no-borrow": "No borrow to repay",
"no-history": "No swap history",
"no-swap-found": "No swap found",
"output-reduce-only-warning": "{{symbol}} is in reduce only mode. You can swap to close borrows only",
"paid": "Paid",
"pay": "You Pay",
"pair": "Pair",
"place-limit-order": "Place Order",
"preset": "Preset",
"price-impact": "Price Impact",
"rate": "Rate",
"receive": "You Receive",
"received": "Received",
"review-swap": "Review Swap",
"route-info": "Route Info",
@ -40,5 +44,7 @@
"tooltip-margin": "When margin is enabled you can add leverage to your swaps. Borrows are opened automatically if a swap exceeds your balance.",
"tooltip-max-slippage": "If price slips beyond your maximum slippage your swap will not be executed",
"use-margin": "Allow Margin",
"no-swap-found": "No swap found"
"warning-no-collateral": "You have no free collateral",
"you-buy": "You're buying",
"you-sell": "You're selling"
}

View File

@ -2,11 +2,14 @@
"24h-volume": "24h Volume",
"activate-volume-alert": "Activate Volume Alert",
"amount": "Amount",
"avg-entry-price": "Avg. Entry Price",
"average-funding": "Average {{interval}} Funding",
"average-price-of": "at an average price of",
"base": "Base",
"book": "Book",
"buys": "Buys",
"cancel-all": "Cancel All",
"cancel-order": "Cancel Order",
"cancel-order-error": "Failed to cancel order",
"close-confirm": "Market close your {{config_name}} position",
"close-position": "Close Position",
@ -19,8 +22,9 @@
"depth": "Depth",
"edit-order": "Edit Order",
"est-liq-price": "Est. Liq. Price",
"avg-entry-price": "Avg. Entry Price",
"est-slippage": "Est. Slippage",
"falls-to": "falls to",
"filled": "Filled",
"for": "for",
"funding-limits": "Funding Limits",
"funding-rate": "1h Avg Funding Rate",
@ -72,7 +76,10 @@
"realized-pnl": "Realized PnL",
"reduce": "Reduce",
"reduce-only": "Reduce Only",
"repay-borrow-order-desc": "Repay {{amount}} {{symbol}} if the oracle price reaches {{triggerPrice}} {{priceUnit}}",
"repay-borrow-deposit-order-desc": "Repay {{borrowAmount}} and buy {{depositAmount}} {{symbol}} if the oracle price reaches {{triggerPrice}} {{priceUnit}}",
"return-on-equity": "Return on Equity",
"rises-to": "rises to",
"sells": "Sells",
"settle-funds": "Settle Funds",
"settle-funds-error": "Failed to settle funds",
@ -83,6 +90,10 @@
"size": "Size",
"spread": "Spread",
"stable-price": "Stable Price",
"stop-limit": "Stop Limit",
"stop-loss": "Stop Loss",
"stop-market": "Stop Market",
"take-profit": "Take Profit",
"taker": "Taker",
"taker-fee": "Taker Fee",
"tick-size": "Tick Size",
@ -99,6 +110,10 @@
"total-pnl": "Total PnL",
"trade-sounds-tooltip": "Play a sound alert for every new trade",
"trades": "Trades",
"trigger-price": "Trigger Price",
"trigger-order": "Trigger Order",
"trigger-order-desc": "{{amount}} {{symbol}} if the oracle price {{orderType}} {{triggerPrice}} {{priceUnit}}",
"trigger-orders": "Trigger Orders",
"tweet-position": "Tweet",
"unrealized-pnl": "Unrealized PnL",
"unsettled": "Unsettled",

View File

@ -1,9 +1,11 @@
{
"confirm-swap": "确定换币",
"connect-swap": "连接来查换币纪录",
"deposit-funds": "Deposit Funds",
"disabled": "关闭",
"enabled": "开启",
"est-liq-price": "预计清算价格",
"est-received": "Est. Received",
"fees-paid-to": "缴给{{route}}的费用",
"health-impact": "健康影响",
"hide-fees": "隐藏费用",
@ -16,11 +18,14 @@
"max-slippage": "最多下滑",
"maximum-cost": "最大成本",
"minimum-received": "最小获取",
"no-borrow": "No borrow to repay",
"no-history": "无换币纪录",
"no-swap-found": "查不到换币",
"output-reduce-only-warning": "{{symbol}}处于仅减少模式。换币限于归还借贷",
"paid": "付出",
"pair": "Pair",
"pay": "你将付出",
"place-limit-order": "Place Order",
"preset": "预设",
"price-impact": "价格影响",
"rate": "汇率",
@ -40,5 +45,8 @@
"tooltip-borrow-no-balance": "您将借入 {{borrowAmount}} {{token}} 来执行此交换。当前的 {{token}} 可变借贷利率为 {{rate}}%",
"tooltip-margin": "启用保证金时将能杠杆换币。如果换币数量超过您的余额将会自动借款。",
"tooltip-max-slippage": "如果价格下滑超过您的最大滑点,换币交易将不会被执行",
"use-margin": "允许杠杆"
"use-margin": "允许杠杆",
"warning-no-collateral": "You have no free collateral",
"you-buy": "You're buying",
"you-sell": "You're selling"
}

View File

@ -8,6 +8,8 @@
"base": "基础",
"book": "单薄",
"buys": "买",
"cancel-all": "Cancel All",
"cancel-order": "Cancel Order",
"cancel-order-error": "取消订单失败",
"close-confirm": "市场平仓 {{config_name}}",
"close-position": "平仓",
@ -21,6 +23,8 @@
"edit-order": "编辑订单",
"est-liq-price": "预计清算价格",
"est-slippage": "预计下滑",
"falls-to": "falls to",
"filled": "Filled",
"for": "for",
"funding-limits": "资金费限制",
"funding-rate": "1小时平均资金费",
@ -72,7 +76,10 @@
"realized-pnl": "已实现的盈亏",
"reduce": "Reduce",
"reduce-only": "限减少",
"repay-borrow-order-desc": "Repay {{amount}} {{symbol}} if the oracle price reaches {{triggerPrice}} {{priceUnit}}",
"repay-borrow-deposit-order-desc": "Repay {{borrowAmount}} and buy {{depositAmount}} {{symbol}} if the oracle price reaches {{triggerPrice}} {{priceUnit}}",
"return-on-equity": "Return on Equity",
"rises-to": "rises to",
"sells": "卖单",
"settle-funds": "借清资金",
"settle-funds-error": "借清出错",
@ -80,6 +87,14 @@
"show-asks": "显示要价",
"show-bids": "显示出价",
"side": "方向",
"stop-limit": "Stop Limit",
"stop-loss": "Stop Loss",
"stop-market": "Stop Market",
"take-profit": "Take Profit",
"trigger-price": "Trigger Price",
"trigger-order": "Trigger Order",
"trigger-order-desc": "{{amount}} {{symbol}} if the oracle price {{orderType}} {{triggerPrice}} {{priceUnit}}",
"trigger-orders": "Trigger Orders",
"size": "数量",
"spread": "差价",
"stable-price": "稳定价格",

View File

@ -1,9 +1,11 @@
{
"confirm-swap": "確定換幣",
"connect-swap": "連接來查換幣紀錄",
"deposit-funds": "Deposit Funds",
"disabled": "關閉",
"enabled": "開啟",
"est-liq-price": "預計清算價格",
"est-received": "Est. Received",
"fees-paid-to": "繳給{{route}}的費用",
"health-impact": "健康影響",
"hide-fees": "隱藏費用",
@ -16,11 +18,14 @@
"max-slippage": "最多下滑",
"maximum-cost": "最大成本",
"minimum-received": "最小獲取",
"no-borrow": "No borrow to repay",
"no-history": "無換幣紀錄",
"no-swap-found": "查不到換幣",
"output-reduce-only-warning": "{{symbol}}處於僅減少模式。換幣限於歸還借貸",
"paid": "付出",
"pair": "Pair",
"pay": "你將付出",
"place-limit-order": "Place Order",
"preset": "預設",
"price-impact": "價格影響",
"rate": "匯率",
@ -40,5 +45,8 @@
"tooltip-borrow-no-balance": "您將借入 {{borrowAmount}} {{token}} 來執行此交換。當前的 {{token}} 可變借貸利率為 {{rate}}%",
"tooltip-margin": "啟用保證金時將能槓桿換幣。如果換幣數量超過您的餘額將會自動借款。",
"tooltip-max-slippage": "如果價格下滑超過您的最大滑點,換幣交易將不會被執行",
"use-margin": "允許槓桿"
"use-margin": "允許槓桿",
"warning-no-collateral": "You have no free collateral",
"you-buy": "You're buying",
"you-sell": "You're selling"
}

View File

@ -8,6 +8,8 @@
"base": "基礎",
"book": "單薄",
"buys": "買",
"cancel-all": "Cancel All",
"cancel-order": "Cancel Order",
"cancel-order-error": "取消訂單失敗",
"close-confirm": "市場平倉 {{config_name}}",
"close-position": "平倉",
@ -21,6 +23,8 @@
"edit-order": "編輯訂單",
"est-liq-price": "預計清算價格",
"est-slippage": "預計下滑",
"falls-to": "falls to",
"filled": "Filled",
"for": "for",
"funding-limits": "資金費限制",
"funding-rate": "1小時平均資金費",
@ -72,7 +76,10 @@
"realized-pnl": "已實現的盈虧",
"reduce": "Reduce",
"reduce-only": "限減少",
"repay-borrow-order-desc": "Repay {{amount}} {{symbol}} if the oracle price reaches {{triggerPrice}} {{priceUnit}}",
"repay-borrow-deposit-order-desc": "Repay {{borrowAmount}} and buy {{depositAmount}} {{symbol}} if the oracle price reaches {{triggerPrice}} {{priceUnit}}",
"return-on-equity": "Return on Equity",
"rises-to": "rises to",
"sells": "賣單",
"settle-funds": "借清資金",
"settle-funds-error": "借清出錯",
@ -83,6 +90,10 @@
"size": "數量",
"spread": "差價",
"stable-price": "穩定價格",
"stop-limit": "Stop Limit",
"stop-loss": "Stop Loss",
"stop-market": "Stop Market",
"take-profit": "Take Profit",
"taker": "吃單者",
"taker-fee": "吃單者費用",
"tick-size": "波動單位",
@ -99,6 +110,10 @@
"total-pnl": "總盈虧",
"trade-sounds-tooltip": "為每筆新交易播放警報聲音",
"trades": "交易",
"trigger-price": "Trigger Price",
"trigger-order": "Trigger Order",
"trigger-order-desc": "{{amount}} {{symbol}} if the oracle price {{orderType}} {{triggerPrice}} {{priceUnit}}",
"trigger-orders": "Trigger Orders",
"tweet-position": "分享至Twitter",
"unrealized-pnl": "未實現盈虧",
"unsettled": "未結清",

View File

@ -127,6 +127,7 @@ export const DEFAULT_TRADE_FORM: TradeForm = {
baseSize: '',
quoteSize: '',
tradeType: 'Limit',
triggerPrice: '',
postOnly: false,
ioc: false,
reduceOnly: false,
@ -218,6 +219,7 @@ export type MangoStore = {
swapMode: 'ExactIn' | 'ExactOut'
amountIn: string
amountOut: string
flipPrices: boolean
}
set: (x: (x: MangoStore) => void) => void
themeData: ThemeData
@ -384,6 +386,7 @@ const mangoStore = create<MangoStore>()(
swapMode: 'ExactIn',
amountIn: '',
amountOut: '',
flipPrices: false,
},
themeData: nftThemeMeta.default,
tokenStats: {

View File

@ -387,6 +387,7 @@ export interface TradeForm {
baseSize: string
quoteSize: string
tradeType: 'Market' | 'Limit'
triggerPrice?: string
postOnly: boolean
ioc: boolean
reduceOnly: boolean

View File

@ -6,10 +6,10 @@ export const CLIENT_TX_TIMEOUT = 90000
export const SECONDS = 1000
export const INPUT_TOKEN_DEFAULT = 'USDC'
export const INPUT_TOKEN_DEFAULT = 'SOL'
export const MANGO_MINT = 'MangoCzJ36AjZyKwVj3VnYU4GTonjfVEnJmvvWaxLac'
export const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'
export const OUTPUT_TOKEN_DEFAULT = 'SOL'
export const OUTPUT_TOKEN_DEFAULT = 'MNGO'
export const JUPITER_V4_PROGRAM_ID =
'JUP4Fb2cqiRUcaTHdrPC8h2gNsA2ETXiPDD33WcGuJB'

View File

@ -34,10 +34,10 @@
bn.js "^5.2.1"
eslint-config-prettier "^9.0.0"
"@blockworks-foundation/mango-v4@^0.19.2":
version "0.19.2"
resolved "https://registry.yarnpkg.com/@blockworks-foundation/mango-v4/-/mango-v4-0.19.2.tgz#2047fdffd43b326ce48f7a774077f89c27906618"
integrity sha512-mEKzpr1IIjb7AO3JKuIK6kvLDAQW/qenDW+Pdr+OCvnlADdHWDR0CJ8MByDVatnlGHw4jJi/eqn8gBYll+8/LQ==
"@blockworks-foundation/mango-v4@^0.19.3":
version "0.19.3"
resolved "https://registry.yarnpkg.com/@blockworks-foundation/mango-v4/-/mango-v4-0.19.3.tgz#c41b002a674b6ca7647a0c6ec007ffd705d1a53a"
integrity sha512-E+0yVLEkomrSuCrAu8odmBb/hZOOt8h4izDqrKC+Af+fg/n8hCylAax+Lt0fbtSgp4V3l4xNPCPHUkTiMA5zOQ==
dependencies:
"@coral-xyz/anchor" "^0.27.0"
"@project-serum/serum" "0.13.65"