import { Dialog, Switch, Transition } from '@headlessui/react' import BigNumber from 'bignumber.js' import React, { useMemo, useState } from 'react' import { NumericFormat } from 'react-number-format' import { toast } from 'react-toastify' import { Button } from 'components/Button' import { CircularProgress } from 'components/CircularProgress' import { ContainerSecondary } from 'components/ContainerSecondary' import { Gauge } from 'components/Gauge' import { PositionsList } from 'components/PositionsList' import { ProgressBar } from 'components/ProgressBar' import { Slider } from 'components/Slider' import { Text } from 'components/Text' import { Tooltip } from 'components/Tooltip' import { useAccountStats } from 'hooks/data/useAccountStats' import { useBalances } from 'hooks/data/useBalances' import { useCalculateMaxBorrowAmount } from 'hooks/data/useCalculateMaxBorrowAmount' import { useBorrowFunds } from 'hooks/mutations/useBorrowFunds' import { useAllBalances } from 'hooks/queries/useAllBalances' import { useMarkets } from 'hooks/queries/useMarkets' import { useTokenPrices } from 'hooks/queries/useTokenPrices' import { formatCurrency, formatValue } from 'utils/formatters' import { getTokenDecimals, getTokenSymbol } from 'utils/tokens' import useStore from 'store' import { getBaseAsset, getMarketAssets } from 'utils/assets' type Props = { show: boolean onClose: () => void tokenDenom: string } export const BorrowModal = ({ show, onClose, tokenDenom }: Props) => { const [amount, setAmount] = useState(0) const [isBorrowToCreditAccount, setIsBorrowToCreditAccount] = useState(false) const selectedAccount = useStore((s) => s.selectedAccount) const marketAssets = getMarketAssets() const baseAsset = getBaseAsset() const balances = useBalances() const { actions, borrowAmount } = useMemo(() => { const borrowAmount = BigNumber(amount) .times(10 ** getTokenDecimals(tokenDenom, marketAssets)) .toNumber() const withdrawAmount = isBorrowToCreditAccount ? 0 : borrowAmount return { borrowAmount, withdrawAmount, actions: [ { type: 'borrow', amount: borrowAmount, denom: tokenDenom, }, { type: 'withdraw', amount: withdrawAmount, denom: tokenDenom, }, ] as AccountStatsAction[], } }, [amount, isBorrowToCreditAccount, tokenDenom, marketAssets]) const accountStats = useAccountStats(actions) const tokenSymbol = getTokenSymbol(tokenDenom, marketAssets) const { mutate, isLoading } = useBorrowFunds(borrowAmount, tokenDenom, !isBorrowToCreditAccount, { onSuccess: () => { onClose() toast.success(`${amount} ${tokenSymbol} successfully Borrowed`) }, }) const { data: tokenPrices } = useTokenPrices() const { data: balancesData } = useAllBalances() const { data: marketsData } = useMarkets() const handleSubmit = () => { mutate() } const walletAmount = useMemo(() => { return BigNumber(balancesData?.find((balance) => balance.denom === tokenDenom)?.amount ?? 0) .div(10 ** getTokenDecimals(tokenDenom, marketAssets)) .toNumber() }, [balancesData, tokenDenom, marketAssets]) const tokenPrice = tokenPrices?.[tokenDenom] ?? 0 const borrowRate = Number(marketsData?.[tokenDenom]?.borrow_rate) const maxValue = useCalculateMaxBorrowAmount(tokenDenom, isBorrowToCreditAccount) const percentageValue = useMemo(() => { if (isNaN(amount) || maxValue === 0) return 0 return (amount * 100) / maxValue }, [amount, maxValue]) const handleValueChange = (value: number) => { if (value > maxValue) { setAmount(maxValue) return } setAmount(value) } const handleSliderValueChange = (value: number[]) => { const decimal = value[0] / 100 const tokenDecimals = getTokenDecimals(tokenDenom, marketAssets) // limit decimal precision based on token contract decimals const newAmount = Number((decimal * maxValue).toFixed(tokenDecimals)) setAmount(newAmount) } const handleBorrowTargetChange = () => { setIsBorrowToCreditAccount((c) => !c) // reset amount due to max value calculations changing depending on borrow target setAmount(0) } return (
{isLoading && (
)}
Borrow {tokenSymbol}

In wallet: {walletAmount.toLocaleString()} {tokenSymbol}

Borrow Rate: {(borrowRate * 100).toFixed(2)}%

Amount

handleValueChange(v.floatValue || 0)} suffix={` ${tokenSymbol}`} decimalScale={getTokenDecimals(tokenDenom, marketAssets)} />
1 {tokenSymbol} = {formatCurrency(tokenPrice)}
{formatCurrency(tokenPrice * amount)}
setAmount(maxValue)} />
Borrow to Credit Account{' '} OFF = Borrow directly into your wallet by using your account Assets as collateral. The borrowed asset will become a liability in your account. ON = Borrow into your Account. The borrowed asset will be available in the account as an Asset and appear also as a liability in your account. } />

About

Account {selectedAccount}

{accountStats && (

{formatCurrency( BigNumber(accountStats.netWorth) .dividedBy(10 ** baseAsset.decimals) .toNumber(), )}

Current Leverage:{' '} {formatValue(accountStats.currentLeverage, 0, 2, true, false, 'x')}
Max Leverage:{' '} {formatValue(accountStats.maxLeverage, 0, 2, true, false, 'x')} } /> Current Risk:{' '} {formatValue(accountStats.risk * 100, 0, 2, true, false, '%')} } />
)}
Total Position:
{formatCurrency( BigNumber(accountStats?.totalPosition ?? 0) .dividedBy(10 ** baseAsset.decimals) .toNumber(), )}
Total Liabilities:
{formatCurrency( BigNumber(accountStats?.totalDebt ?? 0) .dividedBy(10 ** baseAsset.decimals) .toNumber(), )}
) }