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, CircularProgress, ContainerSecondary, Gauge, PositionsList, ProgressBar, Slider, Text, Tooltip, } from 'components' import { useAccountStats, useBalances, useCalculateMaxBorrowAmount } from 'hooks/data' import { useBorrowFunds } from 'hooks/mutations' import { useAllBalances, useMarkets, useTokenPrices } from 'hooks/queries' import { useAccountDetailsStore, useNetworkConfigStore } from 'stores' import { formatCurrency, formatValue } from 'utils/formatters' import { getTokenDecimals, getTokenSymbol } from 'utils/tokens' 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 = useAccountDetailsStore((s) => s.selectedAccount) const whitelistedAssets = useNetworkConfigStore((s) => s.assets.whitelist) const baseAsset = useNetworkConfigStore((s) => s.assets.base) const balances = useBalances() const { actions, borrowAmount } = useMemo(() => { const borrowAmount = BigNumber(amount) .times(10 ** getTokenDecimals(tokenDenom, whitelistedAssets)) .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, whitelistedAssets]) const accountStats = useAccountStats(actions) const tokenSymbol = getTokenSymbol(tokenDenom, whitelistedAssets) 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, whitelistedAssets)) .toNumber() }, [balancesData, tokenDenom, whitelistedAssets]) 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, whitelistedAssets) // 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, whitelistedAssets)} />
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(), )}
) }