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

396 lines
12 KiB
TypeScript
Raw Normal View History

2022-08-02 11:04:00 -07:00
import { useState, ChangeEvent, useCallback, useEffect, useMemo } from 'react'
2022-08-11 19:27:36 -07:00
import { TransactionInstruction } from '@solana/web3.js'
2022-08-08 10:42:18 -07:00
import { ArrowDownIcon, CogIcon } from '@heroicons/react/solid'
2022-08-03 14:46:37 -07:00
import mangoStore from '../../store/state'
import { RouteInfo } from '@jup-ag/core'
2022-07-05 20:37:49 -07:00
import ContentBox from '../shared/ContentBox'
import { notify } from '../../utils/notifications'
import JupiterRouteInfo from './JupiterRouteInfo'
2022-07-05 20:37:49 -07:00
import TokenSelect from '../TokenSelect'
import useDebounce from '../shared/useDebounce'
2022-08-11 19:27:36 -07:00
import { floorToDecimal, numberFormat } from '../../utils/numbers'
2022-08-15 15:18:23 -07:00
import { SwapLeverageSlider } from './LeverageSlider'
2022-07-15 05:50:29 -07:00
import Input from '../forms/Input'
import { useTranslation } from 'next-i18next'
2022-07-16 04:22:59 -07:00
import SelectToken from './SelectToken'
import { Transition } from '@headlessui/react'
2022-08-12 05:40:26 -07:00
import Button, { IconButton, LinkButton } from '../shared/Button'
2022-07-17 04:48:33 -07:00
import ButtonGroup from '../forms/ButtonGroup'
2022-07-18 03:02:43 -07:00
import Loading from '../shared/Loading'
2022-07-23 19:48:26 -07:00
import { EnterBottomExitBottom } from '../shared/Transitions'
2022-08-03 14:46:37 -07:00
import useJupiter from './useJupiter'
2022-08-08 10:42:18 -07:00
import SwapSettings from './SwapSettings'
2022-08-15 04:28:36 -07:00
import SheenLoader from '../shared/SheenLoader'
2022-07-18 03:02:43 -07:00
2022-07-05 20:37:49 -07:00
const Swap = () => {
2022-07-15 05:50:29 -07:00
const { t } = useTranslation('common')
2022-07-18 03:02:43 -07:00
const [selectedRoute, setSelectedRoute] = useState<RouteInfo>()
2022-07-05 20:37:49 -07:00
const [amountIn, setAmountIn] = useState('')
const [submitting, setSubmitting] = useState(false)
2022-07-22 08:40:53 -07:00
const [animateSwitchArrow, setAnimateSwitchArrow] = useState(0)
2022-07-16 04:22:59 -07:00
const [showTokenSelect, setShowTokenSelect] = useState('')
2022-08-08 10:42:18 -07:00
const [showSettings, setShowSettings] = useState(false)
2022-07-17 19:49:14 -07:00
const [showConfirm, setShowConfirm] = useState(false)
2022-07-22 08:40:53 -07:00
2022-07-10 19:01:16 -07:00
const set = mangoStore.getState().set
const useMargin = mangoStore((s) => s.swap.margin)
const slippage = mangoStore((s) => s.swap.slippage)
2022-07-25 22:27:53 -07:00
const inputToken = mangoStore((s) => s.swap.inputToken)
const outputToken = mangoStore((s) => s.swap.outputToken)
2022-08-02 11:04:00 -07:00
const jupiterTokens = mangoStore((s) => s.jupiterTokens)
2022-07-17 19:49:14 -07:00
const connected = mangoStore((s) => s.connected)
const debouncedAmountIn: string = useDebounce(amountIn, 300)
2022-07-05 20:37:49 -07:00
2022-08-03 14:46:37 -07:00
const { amountOut, jupiter, outputTokenInfo, routes } = useJupiter({
inputTokenSymbol: inputToken,
outputTokenSymbol: outputToken,
inputAmount: debouncedAmountIn,
2022-08-03 14:46:37 -07:00
slippage,
})
2022-07-18 03:02:43 -07:00
useEffect(() => {
2022-08-03 14:46:37 -07:00
setSelectedRoute(routes[0])
}, [routes])
2022-07-18 03:02:43 -07:00
2022-07-12 19:02:36 -07:00
const handleAmountInChange = useCallback(
(e: ChangeEvent<HTMLInputElement>) => {
setAmountIn(e.target.value)
},
[]
)
2022-07-05 20:37:49 -07:00
2022-08-10 13:23:19 -07:00
const handleTokenInSelect = (mintAddress: string) => {
const inputTokenInfo = jupiterTokens.find(
(t: any) => t.address === mintAddress
)
const group = mangoStore.getState().group
if (group) {
const banks = Array.from(group.banksMap.values())
2022-08-10 13:23:19 -07:00
const bank = banks.find((b) => b.mint.toString() === mintAddress)
set((s) => {
s.swap.inputToken = bank!.name
s.swap.inputTokenInfo = inputTokenInfo
})
}
2022-07-16 04:22:59 -07:00
setShowTokenSelect('')
2022-07-05 20:37:49 -07:00
}
2022-08-10 13:23:19 -07:00
const handleTokenOutSelect = (mintAddress: string) => {
const outputTokenInfo = jupiterTokens.find(
(t: any) => t.address === mintAddress
)
const group = mangoStore.getState().group
if (group) {
const banks = Array.from(group.banksMap.values())
2022-08-10 13:23:19 -07:00
const bank = banks.find((b) => b.mint.toString() === mintAddress)
set((s) => {
s.swap.outputToken = bank!.name
s.swap.outputTokenInfo = outputTokenInfo
})
}
2022-07-16 04:22:59 -07:00
setShowTokenSelect('')
2022-07-05 20:37:49 -07:00
}
2022-07-10 19:01:16 -07:00
const handleSwitchTokens = () => {
2022-08-02 11:04:00 -07:00
const inputTokenInfo = jupiterTokens.find(
(t: any) => t.symbol === inputToken
)
const outputTokenInfo = jupiterTokens.find(
(t: any) => t.symbol === outputToken
)
set((s) => {
2022-07-25 22:27:53 -07:00
s.swap.inputToken = outputToken
s.swap.outputToken = inputToken
s.swap.inputTokenInfo = outputTokenInfo
s.swap.outputTokenInfo = inputTokenInfo
})
2022-07-16 21:41:20 -07:00
2022-07-22 08:40:53 -07:00
setAnimateSwitchArrow(animateSwitchArrow + 1)
2022-07-10 19:01:16 -07:00
}
2022-07-05 20:37:49 -07:00
const handleSwap = async (
userDefinedInstructions: TransactionInstruction[]
) => {
const client = mangoStore.getState().client
const group = mangoStore.getState().group
const actions = mangoStore.getState().actions
2022-07-27 23:35:18 -07:00
const mangoAccount = mangoStore.getState().mangoAccount.current
2022-07-05 20:37:49 -07:00
if (!mangoAccount || !group) return
try {
setSubmitting(true)
2022-08-04 09:42:03 -07:00
const tx = await client.marginTrade({
2022-07-05 20:37:49 -07:00
group,
mangoAccount,
inputToken,
amountIn: parseFloat(amountIn),
2022-07-10 19:01:16 -07:00
outputToken,
2022-07-05 20:37:49 -07:00
userDefinedInstructions,
})
console.log('Success swapping:', tx)
2022-07-10 19:01:16 -07:00
notify({
title: 'Transaction confirmed',
type: 'success',
txid: tx,
})
2022-07-05 20:37:49 -07:00
await actions.reloadAccount()
} catch (e: any) {
console.log('Error swapping:', e)
notify({
title: 'Transaction failed',
description: e.message,
2022-08-10 13:42:15 -07:00
txid: e?.signature,
2022-07-05 20:37:49 -07:00
type: 'error',
})
} finally {
setSubmitting(false)
}
}
2022-07-18 03:02:43 -07:00
const isLoadingTradeDetails =
2022-08-11 17:52:52 -07:00
Number(amountIn) &&
2022-07-18 03:02:43 -07:00
connected &&
(!routes?.length || !selectedRoute || !outputTokenInfo)
2022-07-05 20:37:49 -07:00
return (
2022-07-17 19:49:14 -07:00
<ContentBox showBackground className="relative overflow-hidden">
2022-07-23 19:51:54 -07:00
<Transition
2022-07-17 19:49:14 -07:00
className="thin-scroll absolute top-0 left-0 z-20 h-full w-full overflow-auto bg-th-bkg-2 p-6 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"
2022-07-17 19:49:14 -07:00
>
<JupiterRouteInfo
2022-07-17 19:49:14 -07:00
inputToken={inputToken}
onClose={() => setShowConfirm(false)}
outputToken={outputToken}
amountIn={Number(debouncedAmountIn)}
2022-07-17 19:49:14 -07:00
slippage={slippage}
handleSwap={handleSwap}
submitting={submitting}
2022-07-18 03:02:43 -07:00
outputTokenInfo={outputTokenInfo}
jupiter={jupiter}
routes={routes}
selectedRoute={selectedRoute}
setSelectedRoute={setSelectedRoute}
2022-07-17 19:49:14 -07:00
/>
2022-07-23 19:51:54 -07:00
</Transition>
2022-07-23 19:48:26 -07:00
<EnterBottomExitBottom
2022-08-02 11:04:00 -07:00
className="thin-scroll absolute bottom-0 left-0 z-20 h-full w-full overflow-auto bg-th-bkg-2 p-6 pb-0"
2022-07-16 04:22:59 -07:00
show={!!showTokenSelect}
>
<SelectToken
onClose={() => setShowTokenSelect('')}
onTokenSelect={
showTokenSelect === 'input'
? handleTokenInSelect
: handleTokenOutSelect
}
type={showTokenSelect}
/>
2022-07-23 19:48:26 -07:00
</EnterBottomExitBottom>
2022-07-17 04:48:33 -07:00
<div className="mb-4 flex items-center justify-between">
<h3>{t('trade')}</h3>
2022-08-12 05:40:26 -07:00
<IconButton
2022-08-14 04:56:19 -07:00
className="text-th-fgd-3"
2022-08-08 10:42:18 -07:00
onClick={() => setShowSettings(true)}
2022-08-14 04:56:19 -07:00
size="small"
2022-07-17 04:48:33 -07:00
>
2022-08-12 05:40:26 -07:00
<CogIcon className="h-5 w-5" />
</IconButton>
2022-07-17 04:48:33 -07:00
</div>
2022-08-08 10:42:18 -07:00
<EnterBottomExitBottom
className="thin-scroll absolute bottom-0 left-0 z-20 h-full w-full overflow-auto bg-th-bkg-2 p-6 pb-0"
show={showSettings}
>
<SwapSettings onClose={() => setShowSettings(false)} />
</EnterBottomExitBottom>
2022-07-17 04:48:33 -07:00
<div className="mb-2 flex items-center justify-between">
<p className="text-th-fgd-3">{t('sell')}</p>
2022-08-02 12:20:27 -07:00
<MaxWalletBalance inputToken={inputToken} setAmountIn={setAmountIn} />
2022-07-17 04:48:33 -07:00
</div>
2022-07-15 05:50:29 -07:00
<div className="mb-3 grid grid-cols-2">
2022-07-23 19:48:26 -07:00
<div className="col-span-1 rounded-lg rounded-r-none border border-r-0 border-th-bkg-4 bg-th-bkg-1">
2022-07-16 04:22:59 -07:00
<TokenSelect
token={inputToken}
showTokenList={setShowTokenSelect}
type="input"
/>
2022-07-05 20:37:49 -07:00
</div>
2022-07-15 05:50:29 -07:00
<div className="col-span-1">
<Input
type="text"
name="amountIn"
id="amountIn"
2022-07-23 19:48:26 -07:00
className="w-full rounded-lg rounded-l-none border border-th-bkg-4 bg-th-bkg-1 p-3 text-right text-xl font-bold tracking-wider text-th-fgd-1 focus:outline-none"
2022-07-15 05:50:29 -07:00
placeholder="0.00"
value={amountIn}
onChange={handleAmountInChange}
/>
2022-07-10 19:01:16 -07:00
</div>
2022-07-17 04:48:33 -07:00
{!useMargin ? (
2022-08-15 09:02:46 -07:00
<PercentageSelectButtons
setAmountIn={setAmountIn}
inputToken={inputToken}
/>
2022-07-17 04:48:33 -07:00
) : null}
2022-07-15 05:50:29 -07:00
</div>
<div className="flex justify-center">
<button
className="rounded-full border border-th-bkg-4 p-1.5 text-th-fgd-3 md:hover:text-th-primary"
onClick={handleSwitchTokens}
>
2022-07-16 21:41:20 -07:00
<ArrowDownIcon
className="h-5 w-5"
style={
2022-07-22 08:40:53 -07:00
animateSwitchArrow % 2 == 0
2022-07-16 21:41:20 -07:00
? { transform: 'rotate(0deg)' }
: { transform: 'rotate(360deg)' }
}
/>
2022-07-15 05:50:29 -07:00
</button>
</div>
2022-07-17 04:48:33 -07:00
<p className="mb-2 text-th-fgd-3">{t('buy')}</p>
2022-07-15 05:50:29 -07:00
<div className="mb-3 grid grid-cols-2">
2022-07-23 19:48:26 -07:00
<div className="col-span-1 rounded-lg rounded-r-none border border-r-0 border-th-bkg-4 bg-th-bkg-1">
2022-07-16 04:22:59 -07:00
<TokenSelect
token={outputToken}
showTokenList={setShowTokenSelect}
type="output"
/>
2022-07-15 05:50:29 -07:00
</div>
2022-08-15 04:28:36 -07:00
<div className="flex w-full items-center justify-end rounded-r-lg border border-th-bkg-4 bg-th-bkg-3 text-right text-xl font-bold tracking-wider text-th-fgd-3">
{isLoadingTradeDetails ? (
<div className="w-full">
<SheenLoader className="rounded-l-none">
<div className="h-[52px] w-full rounded-r-lg bg-th-bkg-3" />
</SheenLoader>
</div>
) : (
<span className="p-3">
{amountOut ? numberFormat.format(amountOut) : 0}
</span>
)}
2022-07-05 20:37:49 -07:00
</div>
</div>
2022-07-17 04:48:33 -07:00
{useMargin ? (
<>
2022-08-16 20:42:16 -07:00
<div className="mb-1 flex items-center justify-between">
2022-07-17 04:48:33 -07:00
<p className="text-th-fgd-3">{t('leverage')}</p>
2022-08-15 19:41:06 -07:00
<p className="text-th-fgd-1">0.00x</p>
2022-07-17 04:48:33 -07:00
</div>
2022-08-15 15:18:23 -07:00
<SwapLeverageSlider
2022-08-17 18:21:16 -07:00
amount={parseFloat(amountIn)}
2022-07-17 04:48:33 -07:00
inputToken={inputToken}
outputToken={outputToken}
onChange={(x) => setAmountIn(x)}
/>
</>
) : null}
2022-07-17 19:49:14 -07:00
<Button
onClick={() => setShowConfirm(true)}
2022-07-23 19:51:54 -07:00
className="mt-6 flex w-full items-center justify-center text-base"
2022-07-18 03:02:43 -07:00
disabled={
!connected || !routes?.length || !selectedRoute || !outputTokenInfo
}
2022-07-20 21:50:56 -07:00
size="large"
2022-07-17 19:49:14 -07:00
>
2022-07-18 03:02:43 -07:00
{connected ? (
isLoadingTradeDetails ? (
<Loading />
) : (
t('trade:review-trade')
)
) : (
t('connect')
)}
2022-07-17 19:49:14 -07:00
</Button>
2022-07-05 20:37:49 -07:00
</ContentBox>
)
}
export default Swap
2022-08-15 09:02:46 -07:00
const useTokenMax = (inputToken: string) => {
const mangoAccount = mangoStore((s) => s.mangoAccount.current)
const tokenInMax = useMemo(() => {
const group = mangoStore.getState().group
const bank = group?.banksMap.get(inputToken)
2022-08-15 21:19:09 -07:00
if (!group || !bank || !mangoAccount) return { amount: 0.0, decimals: 6 }
2022-08-15 09:02:46 -07:00
const balance = mangoAccount.getUi(bank)
2022-08-15 21:19:09 -07:00
return {
amount: floorToDecimal(balance, bank.mintDecimals),
decimals: bank.mintDecimals,
}
2022-08-15 09:02:46 -07:00
}, [inputToken, mangoAccount])
return tokenInMax
}
const MaxWalletBalance = ({
inputToken,
setAmountIn,
}: {
inputToken: string
setAmountIn: (x: any) => void
}) => {
const { t } = useTranslation('common')
2022-08-15 21:19:09 -07:00
const { amount: tokenMax } = useTokenMax(inputToken)
2022-08-15 09:02:46 -07:00
const setMaxInputAmount = () => {
setAmountIn(tokenMax)
}
return (
<LinkButton className="no-underline" onClick={setMaxInputAmount}>
<span className="mr-1 font-normal text-th-fgd-4">{t('balance')}:</span>
<span className="text-th-fgd-3 underline">{tokenMax}</span>
</LinkButton>
)
}
const PercentageSelectButtons = ({
inputToken,
setAmountIn,
}: {
inputToken: string
2022-08-15 20:16:20 -07:00
setAmountIn: (x: any) => any
2022-08-15 09:02:46 -07:00
}) => {
const [sizePercentage, setSizePercentage] = useState('')
2022-08-15 21:19:09 -07:00
const { amount: tokenMax, decimals } = useTokenMax(inputToken)
2022-08-15 09:02:46 -07:00
const handleSizePercentage = (percentage: string) => {
setSizePercentage(percentage)
if (tokenMax > 0) {
2022-08-15 21:19:09 -07:00
let amount = (Number(percentage) / 100) * tokenMax
if (percentage !== '100') {
amount = floorToDecimal(amount, decimals)
}
setAmountIn(amount.toString())
2022-08-15 20:16:20 -07:00
} else {
setAmountIn('0')
2022-08-15 09:02:46 -07:00
}
}
return (
<div className="col-span-2 mt-2">
<ButtonGroup
activeValue={sizePercentage}
onChange={(p) => handleSizePercentage(p)}
values={['10', '25', '50', '75', '100']}
unit="%"
/>
</div>
)
}