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

351 lines
11 KiB
TypeScript
Raw Normal View History

2022-08-02 11:04:00 -07:00
import { useState, ChangeEvent, useCallback, useEffect, useMemo } from 'react'
2022-07-05 20:37:49 -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-08-02 11:04:00 -07:00
import { Token } from '../../types/jupiter'
2022-07-05 20:37:49 -07:00
import ContentBox from '../shared/ContentBox'
import { notify } from '../../utils/notifications'
import JupiterRoutes from './JupiterRoutes'
import TokenSelect from '../TokenSelect'
import useDebounce from '../shared/useDebounce'
2022-08-03 14:46:37 -07:00
import {
floorToDecimal,
formatFixedDecimals,
numberFormat,
} from '../../utils/numbers'
2022-07-12 19:02:36 -07:00
import LeverageSlider 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-07-17 04:48:33 -07:00
import Switch from '../forms/Switch'
2022-08-03 14:46:37 -07:00
import Button, { 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 { toUiDecimals } from '@blockworks-foundation/mango-v4'
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-07-18 03:02:43 -07:00
const getBestRoute = (routesInfos: RouteInfo[]) => {
return routesInfos[0]
}
2022-07-05 20:37:49 -07:00
2022-08-02 12:20:27 -07:00
const MaxWalletBalance = ({
inputToken,
setAmountIn,
}: {
inputToken: string
setAmountIn: (x: any) => void
}) => {
const { t } = useTranslation('common')
const mangoAccount = mangoStore((s) => s.mangoAccount.current)
const tokenInMax = useMemo(() => {
const group = mangoStore.getState().group
const bank = group?.banksMap.get(inputToken)
2022-08-03 14:46:37 -07:00
if (!group || !bank || !mangoAccount) return 0.0
2022-08-02 12:20:27 -07:00
const balance = mangoAccount.getUi(bank)
2022-08-03 14:46:37 -07:00
return floorToDecimal(balance, bank.mintDecimals)
2022-08-02 12:20:27 -07:00
}, [inputToken, mangoAccount])
const setMaxInputAmount = () => {
2022-08-03 14:46:37 -07:00
setAmountIn(tokenInMax)
2022-08-02 12:20:27 -07:00
}
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">
{formatFixedDecimals(tokenInMax)}
</span>
</LinkButton>
)
}
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 04:48:33 -07:00
const [useMargin, setUseMargin] = useState(true)
const [sizePercentage, setSizePercentage] = useState('')
2022-07-17 19:49:14 -07:00
const [showConfirm, setShowConfirm] = useState(false)
2022-07-05 20:37:49 -07:00
const [slippage, setSlippage] = useState(0.1)
2022-07-22 08:40:53 -07:00
2022-07-10 19:01:16 -07:00
const set = mangoStore.getState().set
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)
2022-08-08 10:42:18 -07:00
const debouncedAmountIn = 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: Number(debouncedAmountIn),
slippage,
})
2022-07-18 03:02:43 -07:00
useEffect(() => {
2022-08-03 14:46:37 -07:00
console.log('setting selected route')
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
const handleTokenInSelect = (symbol: string) => {
2022-08-02 11:04:00 -07:00
const inputTokenInfo = jupiterTokens.find((t: any) => t.symbol === symbol)
2022-07-10 19:01:16 -07:00
set((s) => {
2022-07-25 22:27:53 -07:00
s.swap.inputToken = symbol
s.swap.inputTokenInfo = inputTokenInfo
2022-07-10 19:01:16 -07:00
})
2022-07-16 04:22:59 -07:00
setShowTokenSelect('')
2022-07-05 20:37:49 -07:00
}
const handleTokenOutSelect = (symbol: string) => {
2022-08-02 11:04:00 -07:00
const outputTokenInfo = jupiterTokens.find((t: any) => t.symbol === symbol)
2022-07-10 19:01:16 -07:00
set((s) => {
2022-07-25 22:27:53 -07:00
s.swap.outputToken = symbol
s.swap.outputTokenInfo = outputTokenInfo
2022-07-10 19:01:16 -07:00
})
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-17 04:48:33 -07:00
const handleSizePercentage = (percentage: string) => {
setSizePercentage(percentage)
// TODO: calc max
const max = 100
const amount = (Number(percentage) / 100) * max
setAmountIn(amount.toFixed())
}
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,
txid: e?.txid,
type: 'error',
})
} finally {
setSubmitting(false)
}
}
2022-07-18 03:02:43 -07:00
const isLoadingTradeDetails =
amountIn &&
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}
2022-07-23 19:51:54 -07:00
enter="transition-all ease-in duration-300"
enterFrom="transform translate-x-full"
enterTo="transform translate-x-0"
leave="transition-all ease-out duration-300"
leaveFrom="transform translate-x-0"
leaveTo="transform translate-x-full"
2022-07-17 19:49:14 -07:00
>
<JupiterRoutes
inputToken={inputToken}
onClose={() => setShowConfirm(false)}
outputToken={outputToken}
amountIn={parseFloat(debouncedAmountIn)}
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-08 10:42:18 -07:00
<div
className="hover:cursor-pointer"
onClick={() => setShowSettings(true)}
2022-07-17 04:48:33 -07:00
>
2022-08-08 10:42:18 -07:00
<CogIcon className="h-6 w-6" />
</div>
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 ? (
<div className="col-span-2 mt-2">
<ButtonGroup
activeValue={sizePercentage}
onChange={(p) => handleSizePercentage(p)}
2022-07-24 20:12:50 -07:00
values={['10', '25', '50', '75', '100']}
2022-07-17 04:48:33 -07:00
unit="%"
/>
</div>
) : 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-07-23 19:48:26 -07:00
<div className="w-full rounded-lg rounded-l-none border border-th-bkg-4 bg-th-bkg-3 p-3 text-right text-xl font-bold tracking-wider text-th-fgd-3">
2022-07-15 05:50:29 -07:00
{amountOut ? numberFormat.format(amountOut) : 0}
2022-07-05 20:37:49 -07:00
</div>
</div>
2022-07-17 04:48:33 -07:00
{useMargin ? (
<>
<div className="mb-2 flex items-center justify-between">
<p className="text-th-fgd-3">{t('leverage')}</p>
2022-07-22 13:46:33 -07:00
<p className="text-th-fgd-3">0.00x</p>
2022-07-17 04:48:33 -07:00
</div>
<LeverageSlider
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