mirror of
https://github.com/cerc-io/mars-interface.git
synced 2024-11-17 11:19:20 +00:00
release v1.4.4
This commit is contained in:
parent
b46a6b9461
commit
7fc6bea7f6
@ -1,280 +1,581 @@
|
|||||||
import { TxBroadcastResult } from '@marsprotocol/wallet-connector'
|
import 'chart.js/auto'
|
||||||
import { useQueryClient } from '@tanstack/react-query'
|
|
||||||
import { Action, Notification, TxResponse } from 'components/common'
|
import classNames from 'classnames'
|
||||||
import { findByDenom } from 'functions'
|
|
||||||
import {
|
import {
|
||||||
getRedbankBorrowMsgOptions,
|
BorrowCapacity,
|
||||||
getRedbankDepositMsgOptions,
|
Button,
|
||||||
getRedbankRepayMsgOptions,
|
Card,
|
||||||
getRedbankWithdrawMsgOptions,
|
ConnectButton,
|
||||||
} from 'functions/messages'
|
DisplayCurrency,
|
||||||
import { useEstimateFee } from 'hooks/queries'
|
ErrorMessage,
|
||||||
import { ltvWeightedDepositValue, maintainanceMarginWeightedDepositValue } from 'libs/assetInfo'
|
InputSection,
|
||||||
import { lookup, lookupDecimals } from 'libs/parse'
|
} from 'components/common'
|
||||||
import isEqual from 'lodash.isequal'
|
import { findByDenom } from 'functions'
|
||||||
import { useRouter } from 'next/router'
|
import { maxBorrowableAmount } from 'functions/redbank/maxBorrowableAmount'
|
||||||
import React, { useMemo, useState } from 'react'
|
import { produceBarChartConfig } from 'functions/redbank/produceBarChartConfig'
|
||||||
|
import { produceUpdatedAssetData } from 'functions/redbank/produceUpdatedAssetData'
|
||||||
|
import { useUserBalance } from 'hooks/queries'
|
||||||
|
import {
|
||||||
|
balanceSum,
|
||||||
|
ltvWeightedDepositValue,
|
||||||
|
maintainanceMarginWeightedDepositValue,
|
||||||
|
producePercentData,
|
||||||
|
} from 'libs/assetInfo'
|
||||||
|
import { formatValue, lookup, lookupSymbol } from 'libs/parse'
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
|
import { Bar } from 'react-chartjs-2'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import useStore from 'store'
|
import useStore from 'store'
|
||||||
import { NotificationType, ViewType } from 'types/enums'
|
import colors from 'styles/_assets.module.scss'
|
||||||
import { QUERY_KEYS } from 'types/enums/queryKeys'
|
import { ViewType } from 'types/enums'
|
||||||
|
|
||||||
import styles from './RedbankAction.module.scss'
|
import styles from './Action.module.scss'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
|
amount: number
|
||||||
|
redBankAssets: RedBankAsset[]
|
||||||
|
depositAssets: RedBankAsset[]
|
||||||
|
borrowAssets: RedBankAsset[]
|
||||||
|
setIsMax: (isMax: boolean) => void
|
||||||
|
setCapHit: (capHit: boolean) => void
|
||||||
|
setAmountCallback: (amount: number) => void
|
||||||
|
mmScaledDepositAmount: number
|
||||||
|
ltvScaledDepositAmount: number
|
||||||
|
totalBorrowBaseCurrencyAmount: number
|
||||||
|
actionButtonSpec: ModalActionButton
|
||||||
|
submitted: boolean
|
||||||
|
feeError?: string
|
||||||
activeView: ViewType
|
activeView: ViewType
|
||||||
id: string
|
denom: string
|
||||||
|
decimals: number
|
||||||
|
handleClose: () => void
|
||||||
}
|
}
|
||||||
|
|
||||||
export const RedbankAction = React.memo(
|
export const Action = ({
|
||||||
({ activeView, id }: Props) => {
|
amount,
|
||||||
// ------------------
|
redBankAssets,
|
||||||
// EXTERNAL HOOKS
|
depositAssets,
|
||||||
// ------------------
|
borrowAssets,
|
||||||
|
setIsMax,
|
||||||
|
setCapHit,
|
||||||
|
setAmountCallback,
|
||||||
|
mmScaledDepositAmount,
|
||||||
|
ltvScaledDepositAmount,
|
||||||
|
totalBorrowBaseCurrencyAmount,
|
||||||
|
actionButtonSpec,
|
||||||
|
submitted,
|
||||||
|
feeError,
|
||||||
|
activeView,
|
||||||
|
denom,
|
||||||
|
decimals,
|
||||||
|
handleClose,
|
||||||
|
}: Props) => {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const router = useRouter()
|
|
||||||
const queryClient = useQueryClient()
|
|
||||||
|
|
||||||
// ------------------
|
// ------------------
|
||||||
// STORE STATE
|
// STORE STATE
|
||||||
// ------------------
|
// ------------------
|
||||||
const client = useStore((s) => s.client)
|
const baseCurrency = useStore((s) => s.baseCurrency)
|
||||||
const marketInfo = useStore((s) => s.marketInfo)
|
const marketInfo = useStore((s) => s.marketInfo)
|
||||||
const networkConfig = useStore((s) => s.networkConfig)
|
const marketAssetLiquidity = useStore((s) => s.marketAssetLiquidity)
|
||||||
const otherAssets = useStore((s) => s.otherAssets)
|
|
||||||
const redBankAssets = useStore((s) => s.redBankAssets)
|
|
||||||
const userBalances = useStore((s) => s.userBalances)
|
|
||||||
const userCollateral = useStore((s) => s.userCollateral)
|
const userCollateral = useStore((s) => s.userCollateral)
|
||||||
|
const userWalletAddress = useStore((s) => s.userWalletAddress)
|
||||||
const whitelistedAssets = useStore((s) => s.whitelistedAssets)
|
const whitelistedAssets = useStore((s) => s.whitelistedAssets)
|
||||||
const executeMsg = useStore((s) => s.executeMsg)
|
const convertToBaseCurrency = useStore((s) => s.convertToBaseCurrency)
|
||||||
|
const findUserDebt = useStore((s) => s.findUserDebt)
|
||||||
|
const enableAnimations = useStore((s) => s.enableAnimations)
|
||||||
|
const baseCurrencyDecimals = useStore((s) => s.baseCurrency.decimals)
|
||||||
|
|
||||||
// ------------------
|
// ------------------
|
||||||
// LOCAL STATE
|
// LOCAL STATE
|
||||||
// ------------------
|
// ------------------
|
||||||
const [amount, setAmount] = useState(0)
|
const [currentAssetPrice, setCurrentAssetPrice] = useState(0)
|
||||||
const [submitted, setSubmitted] = useState(false)
|
const [portfolioVisible, setPortfolioVisible] = useState(false)
|
||||||
const [response, setResponse] = useState<TxBroadcastResult>()
|
const [chartsDataLoaded, setChartsDataLoaded] = useState(false)
|
||||||
const [error, setError] = useState<string>()
|
|
||||||
const [isMax, setIsMax] = useState<boolean>(false)
|
|
||||||
const [capHit, setCapHit] = useState<boolean>(false)
|
|
||||||
|
|
||||||
// ------------------
|
const { data: userBalances } = useUserBalance()
|
||||||
|
|
||||||
|
/// ------------------
|
||||||
// VARIABLES
|
// VARIABLES
|
||||||
// ------------------
|
// ------------------
|
||||||
const assets = [...whitelistedAssets, ...otherAssets]
|
const walletBalance = Number(findByDenom(userBalances || [], denom)?.amount.toString()) || 0
|
||||||
const denom = assets.find((asset) => asset.id === id)?.denom || ''
|
const assetBorrowBalance = findUserDebt(denom)
|
||||||
const decimals = lookupDecimals(denom, whitelistedAssets || []) || 6
|
const availableBalanceBaseCurrency = Math.max(
|
||||||
const symbol = assets.find((asset) => asset.id === id)?.symbol || ''
|
ltvScaledDepositAmount - totalBorrowBaseCurrencyAmount,
|
||||||
const walletBallance = Number(findByDenom(userBalances, denom)?.amount.toString())
|
|
||||||
|
|
||||||
// Read only states
|
|
||||||
const borrowAssetName = redBankAssets.find((asset) => asset.denom === denom)
|
|
||||||
const redBankContractAddress = networkConfig?.contracts.redBank
|
|
||||||
const totalScaledDepositbaseCurrencyBalance = useMemo(() => {
|
|
||||||
if (!userCollateral) return 0
|
|
||||||
return ltvWeightedDepositValue(
|
|
||||||
redBankAssets,
|
|
||||||
marketInfo,
|
|
||||||
userCollateral,
|
|
||||||
'depositBalanceBaseCurrency',
|
|
||||||
)
|
|
||||||
}, [redBankAssets, marketInfo, userCollateral])
|
|
||||||
|
|
||||||
const totalMMScaledDepositbaseCurrencyBalance = useMemo(() => {
|
|
||||||
if (!userCollateral) return 0
|
|
||||||
return maintainanceMarginWeightedDepositValue(
|
|
||||||
redBankAssets,
|
|
||||||
marketInfo,
|
|
||||||
userCollateral,
|
|
||||||
'depositBalanceBaseCurrency',
|
|
||||||
)
|
|
||||||
}, [redBankAssets, marketInfo, userCollateral])
|
|
||||||
|
|
||||||
const totalBorrowBaseCurrencyAmount = redBankAssets.reduce(
|
|
||||||
(total, asset) => total + (Number(asset.borrowBalanceBaseCurrency) || 0),
|
|
||||||
0,
|
0,
|
||||||
)
|
)
|
||||||
|
const currentAsset = redBankAssets.find((asset) => asset.denom === denom)
|
||||||
|
|
||||||
// --------------------------------
|
// -------------------------
|
||||||
// Transaction objects
|
// calculate
|
||||||
// --------------------------------
|
// -------------------------
|
||||||
|
const relevantAssetData = useMemo(
|
||||||
|
() =>
|
||||||
|
activeView === ViewType.Deposit || activeView === ViewType.Withdraw
|
||||||
|
? depositAssets
|
||||||
|
: borrowAssets,
|
||||||
|
[depositAssets, borrowAssets, activeView],
|
||||||
|
)
|
||||||
|
|
||||||
const txMsgOptions = useMemo(() => {
|
const relevantBalanceKey = useMemo(
|
||||||
if (!redBankContractAddress || amount <= 0 || !denom) return
|
() =>
|
||||||
|
activeView === ViewType.Deposit || activeView === ViewType.Withdraw
|
||||||
|
? 'depositBalanceBaseCurrency'
|
||||||
|
: 'borrowBalanceBaseCurrency',
|
||||||
|
[activeView],
|
||||||
|
)
|
||||||
|
|
||||||
switch (activeView) {
|
const amountAdjustedAssetData = useMemo(
|
||||||
case ViewType.Deposit:
|
() =>
|
||||||
return getRedbankDepositMsgOptions(amount, denom)
|
produceUpdatedAssetData(
|
||||||
case ViewType.Withdraw:
|
redBankAssets,
|
||||||
return getRedbankWithdrawMsgOptions(amount, denom)
|
[...relevantAssetData],
|
||||||
case ViewType.Repay:
|
|
||||||
return getRedbankRepayMsgOptions(
|
|
||||||
amount,
|
|
||||||
denom,
|
denom,
|
||||||
Number(findByDenom(userBalances, denom)?.amount) || 0,
|
amount * currentAssetPrice, // amount in display currency
|
||||||
isMax,
|
activeView,
|
||||||
|
relevantBalanceKey,
|
||||||
|
baseCurrencyDecimals,
|
||||||
|
),
|
||||||
|
[
|
||||||
|
activeView,
|
||||||
|
amount,
|
||||||
|
relevantAssetData,
|
||||||
|
currentAssetPrice,
|
||||||
|
denom,
|
||||||
|
redBankAssets,
|
||||||
|
relevantBalanceKey,
|
||||||
|
baseCurrencyDecimals,
|
||||||
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const percentData = producePercentData(
|
||||||
|
produceUpdatedAssetData(
|
||||||
|
redBankAssets,
|
||||||
|
[...relevantAssetData],
|
||||||
|
denom,
|
||||||
|
0.0,
|
||||||
|
activeView,
|
||||||
|
relevantBalanceKey,
|
||||||
|
baseCurrencyDecimals,
|
||||||
|
),
|
||||||
|
relevantBalanceKey,
|
||||||
|
)
|
||||||
|
const updatedData = producePercentData(amountAdjustedAssetData, relevantBalanceKey)
|
||||||
|
|
||||||
|
// ---------------------
|
||||||
|
// logic
|
||||||
|
// ---------------------
|
||||||
|
const newTotalMMScaledSupplyBalance = useMemo(
|
||||||
|
() =>
|
||||||
|
// For deposits and withdraws, we need to recalculate the loan limit
|
||||||
|
{
|
||||||
|
if (!userCollateral) return 0
|
||||||
|
// On first deposit of asset, SC does not hold state of collateral.enabled
|
||||||
|
// Therefore, we need to emulate this state
|
||||||
|
const isFirstDeposit =
|
||||||
|
!relevantAssetData.find((asset) => asset.denom === denom) &&
|
||||||
|
activeView === ViewType.Deposit
|
||||||
|
|
||||||
|
return activeView === ViewType.Deposit || activeView === ViewType.Withdraw
|
||||||
|
? maintainanceMarginWeightedDepositValue(
|
||||||
|
amountAdjustedAssetData,
|
||||||
|
marketInfo,
|
||||||
|
userCollateral,
|
||||||
|
relevantBalanceKey,
|
||||||
|
isFirstDeposit ? denom : '',
|
||||||
|
)
|
||||||
|
: mmScaledDepositAmount
|
||||||
|
},
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[activeView, amountAdjustedAssetData, mmScaledDepositAmount],
|
||||||
|
)
|
||||||
|
|
||||||
|
const newTotalLTVScaledSupplyBalance = useMemo(
|
||||||
|
() =>
|
||||||
|
// For deposits and withdraws, we need to recalculate the loan limit
|
||||||
|
{
|
||||||
|
if (!userCollateral) return 0
|
||||||
|
// On first deposit of asset, SC does not hold state of collateral.enabled
|
||||||
|
// Therefore, we need to emulate this state
|
||||||
|
const isFirstDeposit =
|
||||||
|
!relevantAssetData.find((asset) => asset.denom === denom) &&
|
||||||
|
activeView === ViewType.Deposit
|
||||||
|
|
||||||
|
return activeView === ViewType.Deposit || activeView === ViewType.Withdraw
|
||||||
|
? ltvWeightedDepositValue(
|
||||||
|
amountAdjustedAssetData,
|
||||||
|
marketInfo,
|
||||||
|
userCollateral,
|
||||||
|
relevantBalanceKey,
|
||||||
|
isFirstDeposit ? denom : '',
|
||||||
|
)
|
||||||
|
: ltvScaledDepositAmount
|
||||||
|
},
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[activeView, amountAdjustedAssetData, ltvScaledDepositAmount],
|
||||||
|
)
|
||||||
|
|
||||||
|
const debtValue =
|
||||||
|
activeView === ViewType.Borrow || activeView === ViewType.Repay
|
||||||
|
? balanceSum(amountAdjustedAssetData, relevantBalanceKey)
|
||||||
|
: totalBorrowBaseCurrencyAmount
|
||||||
|
|
||||||
|
const calculateMaxBorrowableAmount = useMemo((): number => {
|
||||||
|
const assetLiquidity = Number(findByDenom(marketAssetLiquidity, denom)?.amount || 0)
|
||||||
|
|
||||||
|
return maxBorrowableAmount(assetLiquidity, availableBalanceBaseCurrency, currentAssetPrice)
|
||||||
|
}, [denom, availableBalanceBaseCurrency, currentAssetPrice, marketAssetLiquidity])
|
||||||
|
|
||||||
|
const repayMax = useMemo((): number => {
|
||||||
|
return Math.min(assetBorrowBalance, walletBalance)
|
||||||
|
}, [assetBorrowBalance, walletBalance, denom, baseCurrency.denom])
|
||||||
|
|
||||||
|
const maxWithdrawableAmount = useMemo((): number => {
|
||||||
|
const assetLtvRatio = findByDenom(marketInfo, denom)?.max_loan_to_value || 0
|
||||||
|
const assetLiquidity = Number(findByDenom(marketAssetLiquidity, denom)?.amount || 0)
|
||||||
|
const asset = depositAssets.find((asset) => asset.denom === denom)
|
||||||
|
const assetBalanceOrAvailableLiquidity = Math.min(Number(asset?.depositBalance), assetLiquidity)
|
||||||
|
|
||||||
|
if (totalBorrowBaseCurrencyAmount === 0) {
|
||||||
|
return assetBalanceOrAvailableLiquidity
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we did not receive a usable asset there is nothing more to do.
|
||||||
|
if (!asset || !asset.depositBalance || !asset.denom) return 0
|
||||||
|
|
||||||
|
const withdrawableAmountOfAsset =
|
||||||
|
availableBalanceBaseCurrency / (currentAssetPrice * assetLtvRatio)
|
||||||
|
|
||||||
|
return withdrawableAmountOfAsset < assetBalanceOrAvailableLiquidity
|
||||||
|
? withdrawableAmountOfAsset
|
||||||
|
: assetBalanceOrAvailableLiquidity
|
||||||
|
}, [
|
||||||
|
denom,
|
||||||
|
currentAssetPrice,
|
||||||
|
depositAssets,
|
||||||
|
availableBalanceBaseCurrency,
|
||||||
|
totalBorrowBaseCurrencyAmount,
|
||||||
|
marketInfo,
|
||||||
|
marketAssetLiquidity,
|
||||||
|
])
|
||||||
|
|
||||||
|
const maxUsableAmount = useMemo(() => {
|
||||||
|
if (!currentAsset) return 0
|
||||||
|
return activeView === ViewType.Deposit
|
||||||
|
? walletBalance
|
||||||
|
: activeView === ViewType.Withdraw
|
||||||
|
? maxWithdrawableAmount
|
||||||
|
: activeView === ViewType.Borrow
|
||||||
|
? calculateMaxBorrowableAmount
|
||||||
|
: repayMax
|
||||||
|
}, [
|
||||||
|
walletBalance,
|
||||||
|
maxWithdrawableAmount,
|
||||||
|
calculateMaxBorrowableAmount,
|
||||||
|
repayMax,
|
||||||
|
activeView,
|
||||||
|
currentAsset,
|
||||||
|
])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setCurrentAssetPrice(convertToBaseCurrency({ denom: denom || '', amount: '1' }))
|
||||||
|
}, [denom, convertToBaseCurrency])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!chartsDataLoaded && percentData[0] != 0) {
|
||||||
|
setChartsDataLoaded(true)
|
||||||
|
}
|
||||||
|
}, [percentData, chartsDataLoaded])
|
||||||
|
|
||||||
|
const chartRefBefore = useRef(null)
|
||||||
|
const chartRefAfter = useRef(null)
|
||||||
|
|
||||||
|
// -----------
|
||||||
|
// callbacks
|
||||||
|
// -----------
|
||||||
|
const handleInputAmount = useCallback(
|
||||||
|
(inputAmount: number) => {
|
||||||
|
if (inputAmount >= maxUsableAmount * 0.99) {
|
||||||
|
setIsMax(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
setAmountCallback(Number(formatValue(inputAmount, 0, 0, false, false, false, false, false)))
|
||||||
|
},
|
||||||
|
[maxUsableAmount, setIsMax, setAmountCallback],
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!currentAsset) return <></>
|
||||||
|
|
||||||
|
const amountUntilDepositCap = currentAsset.depositCap - Number(currentAsset.depositLiquidity)
|
||||||
|
|
||||||
|
const onValueEntered = (microValue: number) => {
|
||||||
|
if (microValue >= maxUsableAmount) microValue = maxUsableAmount
|
||||||
|
setAmountCallback(Number(formatValue(microValue, 0, 0, false, false, false, false, false)))
|
||||||
|
setCapHit(amount > amountUntilDepositCap && activeView === ViewType.Deposit)
|
||||||
|
}
|
||||||
|
|
||||||
|
const produceTabActionButton = () => {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
color='primary'
|
||||||
|
className={styles.submitButton}
|
||||||
|
disabled={actionButtonSpec.disabled}
|
||||||
|
onClick={() => actionButtonSpec.clickHandler()}
|
||||||
|
showProgressIndicator={actionButtonSpec.fetching}
|
||||||
|
text={actionButtonSpec.text}
|
||||||
|
/>
|
||||||
|
<ErrorMessage message={feeError} alignment='center' />
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const onEnterAction = () => {
|
||||||
|
if (!actionButtonSpec.disabled) actionButtonSpec.clickHandler()
|
||||||
|
}
|
||||||
|
|
||||||
|
const produceAvailableText = () => {
|
||||||
|
switch (activeView) {
|
||||||
case ViewType.Borrow:
|
case ViewType.Borrow:
|
||||||
return getRedbankBorrowMsgOptions(amount, denom)
|
return t('common.maxLimitAmountSymbol', {
|
||||||
default:
|
amount: formatValue(
|
||||||
return undefined
|
lookup(maxUsableAmount, denom, decimals),
|
||||||
}
|
0,
|
||||||
}, [activeView, amount, redBankContractAddress, denom, isMax, userBalances])
|
decimals,
|
||||||
|
true,
|
||||||
const { data: fee, error: feeError } = useEstimateFee({
|
'',
|
||||||
msg: txMsgOptions?.msg,
|
'',
|
||||||
funds:
|
false,
|
||||||
activeView === ViewType.Deposit || activeView === ViewType.Repay
|
false,
|
||||||
? [{ denom, amount: amount > 0 ? amount.toFixed(0) : '1' }]
|
),
|
||||||
: undefined,
|
symbol: lookupSymbol(denom, whitelistedAssets || []),
|
||||||
contract: redBankContractAddress,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
const produceActionButtonSpec = (): ModalActionButton => {
|
case ViewType.Deposit:
|
||||||
|
return t('common.inWalletAmountSymbol', {
|
||||||
|
amount: formatValue(
|
||||||
|
lookup(walletBalance, denom, decimals),
|
||||||
|
0,
|
||||||
|
decimals,
|
||||||
|
true,
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
symbol: lookupSymbol(denom, whitelistedAssets || []),
|
||||||
|
})
|
||||||
|
|
||||||
|
case ViewType.Withdraw:
|
||||||
|
// Find amount of asset deposited
|
||||||
|
const asset: RedBankAsset | undefined = depositAssets.find((asset) => asset.denom === denom)
|
||||||
|
return t('common.depositedAmountSymbol', {
|
||||||
|
amount: formatValue(
|
||||||
|
lookup(Number(asset?.depositBalance), denom, decimals),
|
||||||
|
0,
|
||||||
|
decimals,
|
||||||
|
true,
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
symbol: lookupSymbol(denom, whitelistedAssets || []),
|
||||||
|
})
|
||||||
|
|
||||||
|
case ViewType.Repay:
|
||||||
|
return t('redbank.borrowedAmountSymbol', {
|
||||||
|
amount: formatValue(
|
||||||
|
lookup(findUserDebt(denom), denom, decimals),
|
||||||
|
0,
|
||||||
|
decimals,
|
||||||
|
true,
|
||||||
|
'',
|
||||||
|
'',
|
||||||
|
false,
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
symbol: lookupSymbol(denom, whitelistedAssets || []),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return ''
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------
|
||||||
|
// Presentation
|
||||||
|
// -------------
|
||||||
|
|
||||||
|
const produceBarChartData = (percentData: Array<number>, labels: string[]) => {
|
||||||
|
const barColors: string[] = []
|
||||||
|
labels.forEach((label) => {
|
||||||
|
barColors.push(colors[label.toLowerCase()])
|
||||||
|
})
|
||||||
return {
|
return {
|
||||||
disabled: amount === 0 || capHit,
|
labels: labels,
|
||||||
fetching: (amount > 0 && typeof fee === 'undefined') || submitted,
|
datasets: [
|
||||||
text: t(`redbank.${activeView.toLowerCase()}`),
|
{
|
||||||
clickHandler: handleAction,
|
axis: 'x',
|
||||||
color: 'primary',
|
barPercentage: 0.8,
|
||||||
}
|
maxBarThickness: 50,
|
||||||
}
|
data: percentData,
|
||||||
|
fill: true,
|
||||||
const handleAction = async () => {
|
backgroundColor: barColors,
|
||||||
if (!redBankContractAddress || !client) {
|
borderWidth: 1,
|
||||||
alert('Uh oh, operation failed')
|
animation: {
|
||||||
return
|
duration: enableAnimations ? 800 : 0,
|
||||||
}
|
|
||||||
|
|
||||||
setSubmitted(true)
|
|
||||||
|
|
||||||
if (!fee || !txMsgOptions) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const res = await executeMsg({
|
|
||||||
msg: txMsgOptions.msg,
|
|
||||||
// @ts-ignore
|
|
||||||
funds: txMsgOptions.funds || [],
|
|
||||||
contract: redBankContractAddress,
|
|
||||||
fee: fee,
|
|
||||||
})
|
|
||||||
|
|
||||||
if (res?.response.code !== 0) {
|
|
||||||
setError(res?.rawLogs)
|
|
||||||
} else {
|
|
||||||
setResponse(res)
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
const e = error as { message: string }
|
|
||||||
setError(e.message as string)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const reset = () => {
|
|
||||||
setAmount(0)
|
|
||||||
setSubmitted(false)
|
|
||||||
setError(undefined)
|
|
||||||
setIsMax(false)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleClose = () => {
|
|
||||||
reset()
|
|
||||||
|
|
||||||
// path on redbank action will always be /redbank/deposit/<denom> etce
|
|
||||||
router.push(`/${router.pathname.split('/')[1]}`)
|
|
||||||
}
|
|
||||||
|
|
||||||
const removeZeroBalanceValues = (
|
|
||||||
assets: RedBankAsset[],
|
|
||||||
key: 'borrowBalance' | 'depositBalance',
|
|
||||||
) => {
|
|
||||||
const finalisedArray: RedBankAsset[] = []
|
|
||||||
for (let i = 0; i < assets.length; i++) {
|
|
||||||
if (Number(assets[i][key] ?? 0) > 0) {
|
|
||||||
finalisedArray.push(assets[i])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return finalisedArray
|
|
||||||
}
|
|
||||||
|
|
||||||
const { depositAssets, borrowAssets } = redBankAssets.reduce(
|
|
||||||
(
|
|
||||||
prev: {
|
|
||||||
depositAssets: RedBankAsset[]
|
|
||||||
borrowAssets: RedBankAsset[]
|
|
||||||
},
|
},
|
||||||
curr,
|
|
||||||
) => {
|
|
||||||
if (Number(curr.depositBalance) > 0) {
|
|
||||||
prev.depositAssets.push(curr)
|
|
||||||
}
|
|
||||||
if (Number(curr.borrowBalance) > 0) {
|
|
||||||
prev.borrowAssets.push(curr)
|
|
||||||
}
|
|
||||||
return prev
|
|
||||||
},
|
},
|
||||||
{ depositAssets: [], borrowAssets: [] },
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const barChartHeight = 40 * percentData.length + 10
|
||||||
|
|
||||||
|
const actionButton = !userWalletAddress ? (
|
||||||
|
<ConnectButton color={'secondary'} />
|
||||||
|
) : (
|
||||||
|
produceTabActionButton()
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const adjustedLabels = amountAdjustedAssetData.map((asset) =>
|
||||||
|
lookupSymbol(asset.denom || '', whitelistedAssets || []),
|
||||||
|
)
|
||||||
|
|
||||||
|
const getTooltip = (): string | undefined => {
|
||||||
|
switch (activeView) {
|
||||||
|
case ViewType.Borrow:
|
||||||
|
return t('redbank.tooltips.borrow.action')
|
||||||
|
case ViewType.Deposit:
|
||||||
|
return t('redbank.tooltips.deposit.action')
|
||||||
|
case ViewType.Withdraw:
|
||||||
|
return t('redbank.tooltips.withdraw.action')
|
||||||
|
case ViewType.Repay:
|
||||||
|
return t('redbank.tooltips.repay.action')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const collapsableStyles = classNames(styles.collapsable, !portfolioVisible && styles.collapsed)
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={styles.cardContainer}>
|
<Card onClick={handleClose} title={activeView} tooltip={getTooltip()}>
|
||||||
<Notification
|
<InputSection
|
||||||
content={t('redbank.noFundsForRepay', {
|
actionButton={actionButton}
|
||||||
symbol: borrowAssetName?.symbol || '',
|
amount={amount}
|
||||||
})}
|
availableText={produceAvailableText()}
|
||||||
showNotification={
|
checkForMaxValue={activeView === ViewType.Deposit || activeView === ViewType.Repay}
|
||||||
walletBallance === 0 && activeView === ViewType.Repay && !response && !error
|
asset={currentAsset}
|
||||||
|
disabled={
|
||||||
|
submitted ||
|
||||||
|
(amountUntilDepositCap <= 0 && activeView === ViewType.Deposit) ||
|
||||||
|
maxUsableAmount < 1
|
||||||
}
|
}
|
||||||
type={NotificationType.Warning}
|
inputCallback={onValueEntered}
|
||||||
|
maxUsableAmount={maxUsableAmount}
|
||||||
|
onEnterHandler={onEnterAction}
|
||||||
|
setAmountCallback={handleInputAmount}
|
||||||
|
amountUntilDepositCap={amountUntilDepositCap}
|
||||||
|
activeView={activeView}
|
||||||
|
walletBalance={walletBalance}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{response || submitted || error ? (
|
{/* SITUATION COMPARISON */}
|
||||||
<TxResponse
|
<div className={styles.newSituation}>
|
||||||
error={error}
|
<div className={styles.borrowCapacityContainer}>
|
||||||
handleClose={handleClose}
|
<div className={styles.borrowCapacity}>
|
||||||
onSuccess={() => {
|
<div className={styles.borrowCapacityTitle}>
|
||||||
queryClient.invalidateQueries([QUERY_KEYS.USER_DEPOSIT])
|
<span className={`overline ${styles.title}`}>
|
||||||
queryClient.invalidateQueries([QUERY_KEYS.REDBANK])
|
{activeView === ViewType.Withdraw || activeView === ViewType.Deposit
|
||||||
queryClient.invalidateQueries([QUERY_KEYS.USER_BALANCE])
|
? t('common.currentDepositBalance')
|
||||||
queryClient.invalidateQueries([QUERY_KEYS.USER_DEBT])
|
: t('common.currentBorrowBalance')}
|
||||||
|
</span>
|
||||||
|
<DisplayCurrency
|
||||||
|
className={styles.value}
|
||||||
|
coin={{
|
||||||
|
denom: baseCurrency.denom,
|
||||||
|
amount: balanceSum(relevantAssetData, relevantBalanceKey).toString(),
|
||||||
}}
|
}}
|
||||||
response={response}
|
prefixClass='sub2'
|
||||||
title={t('common.summaryOfTheTransaction')}
|
valueClass='h4'
|
||||||
actions={[
|
|
||||||
{
|
|
||||||
label: activeView,
|
|
||||||
values: [`${lookup(amount, denom, decimals).toString()} ${symbol}`],
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
/>
|
/>
|
||||||
) : (
|
</div>
|
||||||
<Action
|
<BorrowCapacity
|
||||||
actionButtonSpec={produceActionButtonSpec()}
|
balance={totalBorrowBaseCurrencyAmount}
|
||||||
feeError={!fee ? (feeError as string) : undefined}
|
barHeight={'17px'}
|
||||||
activeView={activeView}
|
limit={ltvScaledDepositAmount}
|
||||||
amount={Number(amount)}
|
max={mmScaledDepositAmount}
|
||||||
borrowAssets={removeZeroBalanceValues(borrowAssets, 'borrowBalance')}
|
showPercentageText
|
||||||
decimals={decimals}
|
fadeTitle
|
||||||
denom={denom}
|
|
||||||
depositAssets={removeZeroBalanceValues(depositAssets, 'depositBalance')}
|
|
||||||
handleClose={handleClose}
|
|
||||||
ltvScaledDepositAmount={totalScaledDepositbaseCurrencyBalance}
|
|
||||||
mmScaledDepositAmount={totalMMScaledDepositbaseCurrencyBalance}
|
|
||||||
redBankAssets={redBankAssets}
|
|
||||||
setAmountCallback={setAmount}
|
|
||||||
setIsMax={setIsMax}
|
|
||||||
submitted={submitted}
|
|
||||||
totalBorrowBaseCurrencyAmount={totalBorrowBaseCurrencyAmount}
|
|
||||||
setCapHit={setCapHit}
|
|
||||||
/>
|
/>
|
||||||
|
</div>
|
||||||
|
<div className={styles.borrowCapacity}>
|
||||||
|
<div className={styles.borrowCapacityTitle}>
|
||||||
|
<span className={`overline ${styles.title}`}>
|
||||||
|
{activeView === ViewType.Withdraw || activeView === ViewType.Deposit
|
||||||
|
? t('common.newDepositBalance')
|
||||||
|
: t('common.newBorrowBalance')}
|
||||||
|
</span>
|
||||||
|
<DisplayCurrency
|
||||||
|
className={styles.value}
|
||||||
|
coin={{
|
||||||
|
denom: baseCurrency.denom,
|
||||||
|
amount: balanceSum(amountAdjustedAssetData, relevantBalanceKey).toString(),
|
||||||
|
}}
|
||||||
|
prefixClass='sub2'
|
||||||
|
valueClass='h4'
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<BorrowCapacity
|
||||||
|
balance={debtValue}
|
||||||
|
barHeight={'17px'}
|
||||||
|
limit={newTotalLTVScaledSupplyBalance}
|
||||||
|
max={newTotalMMScaledSupplyBalance}
|
||||||
|
showPercentageText
|
||||||
|
fadeTitle
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{chartsDataLoaded && (
|
||||||
|
<div className={collapsableStyles}>
|
||||||
|
<div className={styles.portfolio}>
|
||||||
|
<div className={styles.portfolioWrapper}>
|
||||||
|
<span className={`overline ${styles.title}`}>
|
||||||
|
{t('redbank.currentComposition')}
|
||||||
|
</span>
|
||||||
|
<div className={styles.chartWrapper}>
|
||||||
|
<Bar
|
||||||
|
data={produceBarChartData(percentData, adjustedLabels)}
|
||||||
|
height={barChartHeight}
|
||||||
|
options={produceBarChartConfig(percentData)}
|
||||||
|
ref={chartRefBefore}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className={styles.portfolioWrapper}>
|
||||||
|
<span className={`overline ${styles.title}`}>{t('redbank.newComposition')}</span>
|
||||||
|
<div className={styles.chartWrapper}>
|
||||||
|
<Bar
|
||||||
|
data={produceBarChartData(updatedData, adjustedLabels)}
|
||||||
|
height={barChartHeight}
|
||||||
|
options={produceBarChartConfig(updatedData)}
|
||||||
|
ref={chartRefAfter}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)
|
|
||||||
},
|
|
||||||
(prev, next) => isEqual(prev, next),
|
|
||||||
)
|
|
||||||
|
|
||||||
RedbankAction.displayName = 'RedbankAction'
|
{chartsDataLoaded && (
|
||||||
|
<div className={styles.showPortfolio}>
|
||||||
|
<Button
|
||||||
|
onClick={() => setPortfolioVisible(!portfolioVisible)}
|
||||||
|
size='medium'
|
||||||
|
text={!portfolioVisible ? t('common.showComposition') : t('common.closeComposition')}
|
||||||
|
variant='transparent'
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
@ -17,7 +17,7 @@ i18next
|
|||||||
backend: {
|
backend: {
|
||||||
crossDomain: true,
|
crossDomain: true,
|
||||||
loadPath() {
|
loadPath() {
|
||||||
return 'https://raw.githubusercontent.com/mars-protocol/translations/develop/{{lng}}.json'
|
return 'https://raw.githubusercontent.com/mars-protocol/translations/master/{{lng}}.json'
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
react: {
|
react: {
|
||||||
|
Loading…
Reference in New Issue
Block a user