mango-v4-ui/hooks/useBanksWithBalances.ts

93 lines
2.6 KiB
TypeScript
Raw Normal View History

2023-01-29 20:13:38 -08:00
import { Bank } from '@blockworks-foundation/mango-v4'
import { walletBalanceForToken } from '@components/DepositForm'
import { getMaxWithdrawForBank } from '@components/swap/useTokenMax'
import mangoStore from '@store/mangoStore'
import { useMemo } from 'react'
import useMangoAccount from './useMangoAccount'
import useMangoGroup from './useMangoGroup'
2023-10-12 04:51:02 -07:00
import Decimal from 'decimal.js'
2023-01-29 20:13:38 -08:00
export interface BankWithBalance {
balance: number
bank: Bank
borrowedAmount: number
maxBorrow: number
maxWithdraw: number
walletBalance: number
}
export default function useBanksWithBalances(
sortByKey?:
| 'balance'
| 'borrowedAmount'
| 'maxBorrow'
| 'maxWithdraw'
2023-07-21 11:47:53 -07:00
| 'walletBalance',
2023-01-29 20:13:38 -08:00
) {
const { group } = useMangoGroup()
const { mangoAccount } = useMangoAccount()
const walletTokens = mangoStore((s) => s.wallet.tokens)
const banks: BankWithBalance[] = useMemo(() => {
if (group) {
const banksWithBalances = Array.from(
group?.banksMapByName,
([key, value]) => ({
key,
value,
2023-07-21 11:47:53 -07:00
}),
2023-01-29 20:13:38 -08:00
).map((b) => {
const bank = b.value[0]
2023-11-27 03:33:33 -08:00
const balance = mangoAccount ? mangoAccount.getTokenBalanceUi(bank) : 0
2023-05-22 03:19:23 -07:00
2023-01-29 20:13:38 -08:00
const maxBorrow = mangoAccount
? getMaxWithdrawForBank(group, bank, mangoAccount, true).toNumber()
: 0
let maxWithdraw = mangoAccount
2023-01-29 20:13:38 -08:00
? getMaxWithdrawForBank(group, bank, mangoAccount).toNumber()
: 0
if (maxWithdraw < balance) {
maxWithdraw = maxWithdraw * 0.998
}
2023-01-29 20:13:38 -08:00
const borrowedAmount = mangoAccount
2023-10-12 04:51:02 -07:00
? new Decimal(mangoAccount.getTokenBorrowsUi(bank))
.toDecimalPlaces(bank.mintDecimals, Decimal.ROUND_UP)
.toNumber()
2023-01-29 20:13:38 -08:00
: 0
const walletBalance =
walletBalanceForToken(walletTokens, bank.name)?.maxAmount || 0
return {
bank,
balance,
borrowedAmount,
maxBorrow,
maxWithdraw,
walletBalance,
}
})
const sortedBanks = banksWithBalances.sort((a, b) => {
if (sortByKey) {
const aPrice = a.bank.uiPrice
const bPrice = b.bank.uiPrice
const aValue = Math.abs(a[sortByKey]) * aPrice
const bValue = Math.abs(b[sortByKey]) * bPrice
if (aValue > bValue) return -1
if (aValue < bValue) return 1
}
const aName = a.bank.name
const bName = b.bank.name
if (aName > bName) return 1
if (aName < bName) return -1
return 1
})
return sortedBanks
}
return []
2023-12-06 15:26:30 -08:00
}, [group, mangoAccount, walletTokens])
2023-01-29 20:13:38 -08:00
return banks
}