mango-v4-ui/components/swap/MarketSwapForm.tsx

489 lines
15 KiB
TypeScript
Raw Normal View History

import {
useState,
useCallback,
useEffect,
useMemo,
Dispatch,
SetStateAction,
} from 'react'
import { ArrowDownIcon } from '@heroicons/react/20/solid'
2023-07-25 19:48:13 -07:00
import { NumberFormatValues, SourceInfo } from 'react-number-format'
import Decimal from 'decimal.js'
import mangoStore from '@store/mangoStore'
import { SIZE_INPUT_UI_KEY } from '../../utils/constants'
import { useWallet } from '@solana/wallet-adapter-react'
2023-10-16 21:12:46 -07:00
import { JupiterV6RouteInfo } from 'types/jupiter'
import useLocalStorageState from 'hooks/useLocalStorageState'
import SwapSlider from './SwapSlider'
import PercentageSelectButtons from './PercentageSelectButtons'
2023-07-25 19:48:13 -07:00
import BuyTokenInput from './BuyTokenInput'
import SellTokenInput from './SellTokenInput'
2023-08-03 19:06:09 -07:00
import Button from '@components/shared/Button'
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'
2023-08-15 22:27:45 -07:00
import Link from 'next/link'
import SecondaryConnectButton from '@components/shared/SecondaryConnectButton'
import useRemainingBorrowsInPeriod from 'hooks/useRemainingBorrowsInPeriod'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
2023-08-28 04:59:36 -07:00
import { formatCurrencyValue } from 'utils/numbers'
2023-09-06 06:06:57 -07:00
import { SwapFormTokenListType } from './SwapFormTokenList'
2023-09-08 02:39:56 -07:00
import useTokenPositionsFull from 'hooks/useTokenPositionsFull'
2023-10-20 08:11:19 -07:00
import TopBarStore from '@store/topBarStore'
dayjs.extend(relativeTime)
type MarketSwapFormProps = {
2023-09-06 06:06:57 -07:00
setShowTokenSelect: Dispatch<SetStateAction<SwapFormTokenListType>>
2023-10-12 14:38:44 -07:00
onSuccess?: () => void
}
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
2023-10-12 14:38:44 -07:00
const MarketSwapForm = ({
setShowTokenSelect,
onSuccess,
}: MarketSwapFormProps) => {
2023-08-03 19:06:09 -07:00
const { t } = useTranslation(['common', 'swap', 'trade'])
//initial state is undefined null is returned on error
2023-10-16 21:12:46 -07:00
const [selectedRoute, setSelectedRoute] =
useState<JupiterV6RouteInfo | null>()
const [animateSwitchArrow, setAnimateSwitchArrow] = useState(0)
2023-08-03 19:06:09 -07:00
const [showConfirm, setShowConfirm] = useState(false)
const [swapFormSizeUi] = useLocalStorageState(SIZE_INPUT_UI_KEY, 'slider')
const {
margin: useMargin,
2023-08-03 19:06:09 -07:00
slippage,
inputBank,
outputBank,
amountIn: amountInFormValue,
amountOut: amountOutFormValue,
swapMode,
} = mangoStore((s) => s.swap)
const [isDraggingSlider, setIsDraggingSlider] = useState(false)
2023-08-03 19:06:09 -07:00
const { connected, publicKey } = useWallet()
const { mangoAccount } = useMangoAccount()
const quoteAmount =
swapMode === 'ExactIn' ? amountInFormValue : amountOutFormValue
const {
bestRoute,
isFetching: fetchingRoute,
refetch: refetchRoute,
} = useQuoteRoutes({
inputMint: inputBank?.mint.toString(),
outputMint: outputBank?.mint.toString(),
amount: quoteAmount,
2023-08-03 19:06:09 -07:00
slippage,
swapMode,
wallet: publicKey?.toBase58(),
mangoAccount,
enabled: () =>
!!(
inputBank?.mint &&
outputBank?.mint &&
quoteAmount &&
!isDraggingSlider
),
2023-08-03 19:06:09 -07:00
})
const { ipAllowed, ipCountry } = useIpAddress()
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 setAmountInFormValue = useCallback(
(amountIn: string, setSwapMode?: boolean) => {
set((s) => {
s.swap.amountIn = amountIn
if (!parseFloat(amountIn)) {
s.swap.amountOut = ''
}
if (setSwapMode) {
s.swap.swapMode = 'ExactIn'
}
})
},
2023-07-25 19:48:13 -07:00
[],
)
2023-08-01 05:21:19 -07:00
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'
}
})
},
[],
)
2023-07-25 19:48:13 -07:00
const handleAmountInChange = useCallback(
(e: NumberFormatValues, info: SourceInfo) => {
if (info.source !== 'event') return
setAmountInFormValue(e.value)
set((s) => {
s.swap.amountOut = ''
})
2023-07-25 19:48:13 -07:00
if (swapMode === 'ExactOut') {
set((s) => {
s.swap.swapMode = 'ExactIn'
})
}
},
[outputBank, setAmountInFormValue, swapMode],
)
const handleAmountOutChange = useCallback(
(e: NumberFormatValues, info: SourceInfo) => {
if (info.source !== 'event') return
setAmountOutFormValue(e.value)
set((s) => {
s.swap.amountIn = ''
})
2023-07-25 19:48:13 -07:00
if (swapMode === 'ExactIn') {
set((s) => {
s.swap.swapMode = 'ExactOut'
})
}
},
[swapMode, setAmountOutFormValue],
)
const handleSliderDrag = useCallback(() => {
if (!isDraggingSlider) {
setIsDraggingSlider(true)
}
}, [isDraggingSlider])
const handleSliderDragEnd = useCallback(() => {
if (isDraggingSlider) {
setIsDraggingSlider(false)
}
}, [isDraggingSlider])
const handleSliderChange = useCallback(
(amountIn: string) => {
setAmountInFormValue(amountIn, true)
set((s) => {
s.swap.amountOut = ''
})
},
[setAmountInFormValue],
)
2023-08-01 05:21:19 -07:00
const handleMax = useCallback(
(amountIn: string) => {
setAmountInFormValue(amountIn, true)
set((s) => {
s.swap.amountOut = ''
})
2023-08-01 05:21:19 -07:00
},
[setAmountInFormValue],
)
const handleRepay = useCallback(
(amountOut: string) => {
setAmountOutFormValue(amountOut, true)
set((s) => {
s.swap.amountIn = ''
})
2023-08-01 05:21:19 -07:00
},
[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)
2023-10-17 16:24:40 -07:00
if (inputBank && swapMode === 'ExactOut' && bestRoute?.inAmount) {
const inAmount = new Decimal(bestRoute.inAmount)
.div(10 ** inputBank.mintDecimals)
.toString()
setAmountInFormValue(inAmount)
2023-10-17 16:24:40 -07:00
} else if (outputBank && swapMode === 'ExactIn' && bestRoute?.outAmount) {
const outAmount = new Decimal(bestRoute.outAmount)
.div(10 ** outputBank.mintDecimals)
.toString()
setAmountOutFormValue(outAmount)
}
}
}, [bestRoute, swapMode, inputBank, outputBank])
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
s.swap.amountIn = ''
s.swap.amountOut = ''
})
setAnimateSwitchArrow(
2023-07-25 19:48:13 -07:00
(prevanimateSwitchArrow) => prevanimateSwitchArrow + 1,
)
}, [setAmountInFormValue, amountOutAsDecimal, amountInAsDecimal])
const loadingExactIn: boolean = useMemo(() => {
return (
(!!(amountInAsDecimal.toNumber() || amountOutAsDecimal.toNumber()) &&
connected &&
typeof selectedRoute === 'undefined') ||
!!(
swapMode === 'ExactIn' &&
amountInAsDecimal.toNumber() &&
!amountOutAsDecimal.toNumber()
)
)
}, [
amountInAsDecimal,
amountOutAsDecimal,
connected,
selectedRoute,
swapMode,
])
const loadingExactOut: boolean = useMemo(() => {
return (
(!!(amountInAsDecimal.toNumber() || amountOutAsDecimal.toNumber()) &&
connected &&
typeof selectedRoute === 'undefined') ||
!!(
swapMode === 'ExactOut' &&
amountOutAsDecimal.toNumber() &&
!amountInAsDecimal.toNumber()
)
)
}, [
amountInAsDecimal,
amountOutAsDecimal,
connected,
selectedRoute,
swapMode,
])
return (
<>
2023-09-18 18:22:10 -07:00
<SwapReviewRouteInfo
amountIn={amountInAsDecimal}
loadingRoute={fetchingRoute}
2023-10-17 16:24:40 -07:00
onClose={() => setShowConfirm(false)}
onSuccess={onSuccess}
refetchRoute={refetchRoute}
2023-10-16 21:12:46 -07:00
routes={bestRoute ? [bestRoute] : undefined}
2023-09-18 18:22:10 -07:00
selectedRoute={selectedRoute}
setSelectedRoute={setSelectedRoute}
2023-10-17 16:24:40 -07:00
show={showConfirm}
slippage={slippage}
2023-09-18 18:22:10 -07:00
/>
2023-07-25 19:48:13 -07:00
<SellTokenInput
handleAmountInChange={handleAmountInChange}
setShowTokenSelect={setShowTokenSelect}
2023-08-01 05:21:19 -07:00
handleMax={handleMax}
loading={loadingExactOut}
2023-07-25 19:48:13 -07:00
/>
2023-08-23 15:17:04 -07:00
<div className="rounded-b-xl bg-th-bkg-2 p-3 pt-0">
{swapFormSizeUi === 'slider' ? (
<SwapSlider
useMargin={useMargin}
amount={amountInAsDecimal.toNumber()}
onChange={(v) => handleSliderChange(v)}
2023-08-23 15:17:04 -07:00
step={1 / 10 ** (inputBank?.mintDecimals || 6)}
2023-09-07 00:59:04 -07:00
maxAmount={useTokenMax}
handleStartDrag={handleSliderDrag}
handleEndDrag={handleSliderDragEnd}
2023-08-23 15:17:04 -07:00
/>
) : (
<div className="-mt-2">
<PercentageSelectButtons
amountIn={amountInAsDecimal.toString()}
setAmountIn={(v) => handleSliderChange(v)}
2023-08-23 15:17:04 -07:00
useMargin={useMargin}
/>
</div>
)}
</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>
2023-07-25 19:48:13 -07:00
<BuyTokenInput
handleAmountOutChange={handleAmountOutChange}
loading={loadingExactIn}
2023-07-25 19:48:13 -07:00
setShowTokenSelect={setShowTokenSelect}
2023-08-01 05:21:19 -07:00
handleRepay={handleRepay}
2023-07-25 19:48:13 -07:00
/>
2023-08-03 19:06:09 -07:00
{ipAllowed ? (
<SwapFormSubmitButton
loadingSwapDetails={loadingExactIn || loadingExactOut}
2023-08-03 19:06:09 -07:00
useMargin={useMargin}
selectedRoute={selectedRoute}
setShowConfirm={setShowConfirm}
amountIn={amountInAsDecimal}
inputSymbol={inputBank?.name}
amountOut={selectedRoute ? amountOutAsDecimal.toNumber() : undefined}
/>
) : (
<Button
disabled
2023-09-07 20:35:30 -07:00
className="mb-4 mt-6 flex w-full items-center justify-center text-base"
2023-08-03 19:06:09 -07:00
size="large"
>
{t('country-not-allowed', {
country: ipCountry ? `(${ipCountry})` : '',
})}
</Button>
)}
</>
)
}
export default MarketSwapForm
2023-08-03 19:06:09 -07:00
const SwapFormSubmitButton = ({
amountIn,
amountOut,
2023-08-03 19:06:09 -07:00
loadingSwapDetails,
selectedRoute,
setShowConfirm,
}: {
amountIn: Decimal
amountOut: number | undefined
inputSymbol: string | undefined
loadingSwapDetails: boolean
2023-10-16 21:12:46 -07:00
selectedRoute: JupiterV6RouteInfo | undefined | null
2023-08-03 19:06:09 -07:00
setShowConfirm: (x: boolean) => void
useMargin: boolean
}) => {
const { t } = useTranslation('common')
const { mangoAccountAddress } = useMangoAccount()
const { connected } = useWallet()
2023-10-20 08:11:19 -07:00
const { setShowSettingsModal } = TopBarStore()
2023-09-18 13:42:37 -07:00
// const { amount: tokenMax, amountWithBorrow } = useTokenMax(useMargin)
2023-08-15 22:27:45 -07:00
const { inputBank, outputBank } = mangoStore((s) => s.swap)
const { remainingBorrowsInPeriod, timeToNextPeriod } =
useRemainingBorrowsInPeriod(true)
const tokenPositionsFull = useTokenPositionsFull([outputBank, inputBank])
// check if the borrowed amount exceeds the net borrow limit in the current period
const borrowExceedsLimitInPeriod = useMemo(() => {
const mangoAccount = mangoStore.getState().mangoAccount.current
2023-09-09 04:32:28 -07:00
if (!mangoAccount || !inputBank || !remainingBorrowsInPeriod) return false
const balance = mangoAccount.getTokenDepositsUi(inputBank)
const remainingBalance = balance - amountIn.toNumber()
const borrowAmount = remainingBalance < 0 ? Math.abs(remainingBalance) : 0
const borrowAmountNotional = borrowAmount * inputBank.uiPrice
return borrowAmountNotional > remainingBorrowsInPeriod
}, [amountIn, inputBank, mangoAccountAddress, remainingBorrowsInPeriod])
2023-10-17 16:24:40 -07:00
const disabled =
!amountIn.toNumber() ||
!amountOut ||
!selectedRoute ||
!!selectedRoute.error
2023-08-03 19:06:09 -07:00
return (
<>
{connected ? (
<Button
onClick={() => setShowConfirm(true)}
className="mb-4 mt-6 flex w-full items-center justify-center text-base"
disabled={disabled}
size="large"
>
{loadingSwapDetails ? (
2023-08-03 19:06:09 -07:00
<Loading />
) : (
<span>{t('swap:review-swap')}</span>
)}
</Button>
) : (
<SecondaryConnectButton
className="mb-4 mt-6 flex w-full items-center justify-center"
isLarge
/>
)}
2023-08-15 22:27:45 -07:00
{tokenPositionsFull ? (
<div className="pb-4">
<InlineNotification
type="error"
desc={
<>
{t('error-token-positions-full')}{' '}
2023-10-20 08:11:19 -07:00
<Link href={''} onClick={() => setShowSettingsModal(true)}>
2023-08-15 22:27:45 -07:00
{t('manage')}
</Link>
</>
}
/>
</div>
) : null}
2023-08-28 04:59:36 -07:00
{borrowExceedsLimitInPeriod &&
remainingBorrowsInPeriod &&
timeToNextPeriod ? (
<div className="mb-4">
<InlineNotification
type="error"
desc={t('error-borrow-exceeds-limit', {
2023-08-28 04:59:36 -07:00
remaining: formatCurrencyValue(remainingBorrowsInPeriod),
resetTime: dayjs().to(dayjs().add(timeToNextPeriod, 'second')),
})}
/>
</div>
) : null}
2023-10-17 16:24:40 -07:00
{(selectedRoute === null && amountIn.gt(0)) ||
(selectedRoute && !!selectedRoute.error) ? (
2023-08-03 19:06:09 -07:00
<div className="mb-4">
<InlineNotification type="error" desc={t('swap:no-swap-found')} />
</div>
) : null}
</>
)
}