lev-stake-sol/components/StakeForm.tsx

521 lines
20 KiB
TypeScript
Raw Normal View History

2023-09-22 06:33:36 -07:00
import {
ArrowPathIcon,
ChevronDownIcon,
ExclamationCircleIcon,
} from '@heroicons/react/20/solid'
2023-09-12 17:37:41 -07:00
import { useWallet } from '@solana/wallet-adapter-react'
import { useTranslation } from 'next-i18next'
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import NumberFormat, { NumberFormatValues } from 'react-number-format'
import mangoStore from '@store/mangoStore'
import { notify } from '../utils/notifications'
2023-09-14 21:24:29 -07:00
import { TokenAccount, formatTokenSymbol } from '../utils/tokens'
2023-09-12 17:37:41 -07:00
import Label from './forms/Label'
import Button, { IconButton } from './shared/Button'
import Loading from './shared/Loading'
import MaxAmountButton from '@components/shared/MaxAmountButton'
import Tooltip from '@components/shared/Tooltip'
import SolBalanceWarnings from '@components/shared/SolBalanceWarnings'
import useSolBalance from 'hooks/useSolBalance'
import { floorToDecimal, withValueLimit } from 'utils/numbers'
import { isMangoError } from 'types'
import TokenLogo from './shared/TokenLogo'
import SecondaryConnectButton from './shared/SecondaryConnectButton'
import useMangoAccountAccounts from 'hooks/useMangoAccountAccounts'
import InlineNotification from './shared/InlineNotification'
import Link from 'next/link'
import LeverageSlider from './shared/LeverageSlider'
import useMangoGroup from 'hooks/useMangoGroup'
import FormatNumericValue from './shared/FormatNumericValue'
import { stakeAndCreate } from 'utils/transactions'
2023-10-01 21:06:19 -07:00
// import { MangoAccount } from '@blockworks-foundation/mango-v4'
2023-09-12 20:59:43 -07:00
import { AnchorProvider } from '@project-serum/anchor'
2023-09-20 18:33:18 -07:00
import useBankRates from 'hooks/useBankRates'
2023-09-22 06:33:36 -07:00
import { Disclosure } from '@headlessui/react'
2023-09-24 05:55:00 -07:00
import SheenLoader from './shared/SheenLoader'
import useLeverageMax from 'hooks/useLeverageMax'
2023-10-09 22:43:03 -07:00
import { STAKEABLE_TOKENS_DATA } from 'utils/constants'
2023-10-10 12:17:39 -07:00
import { sleep } from 'utils'
2023-09-12 17:37:41 -07:00
const set = mangoStore.getState().set
2023-09-22 06:33:36 -07:00
export const NUMBERFORMAT_CLASSES =
2023-09-25 06:48:39 -07:00
'inner-shadow-top-sm w-full rounded-xl border border-th-bkg-3 bg-th-input-bkg p-3 pl-12 pr-4 text-left font-bold text-xl text-th-fgd-1 focus:outline-none focus-visible:border-th-fgd-4 md:hover:border-th-bkg-4 md:hover:focus-visible:border-th-fgd-4'
2023-09-22 06:33:36 -07:00
2023-09-20 18:33:18 -07:00
interface StakeFormProps {
2023-09-12 17:37:41 -07:00
token: string
}
export const walletBalanceForToken = (
walletTokens: TokenAccount[],
token: string,
): { maxAmount: number; maxDecimals: number } => {
const group = mangoStore.getState().group
const bank = group?.banksMapByName.get(token)?.[0]
let walletToken
if (bank) {
const tokenMint = bank?.mint
walletToken = tokenMint
? walletTokens.find((t) => t.mint.toString() === tokenMint.toString())
: null
}
return {
maxAmount: walletToken ? walletToken.uiAmount : 0,
maxDecimals: bank?.mintDecimals || 6,
}
}
2023-10-01 21:06:19 -07:00
// const getNextAccountNumber = (accounts: MangoAccount[]): number => {
// if (accounts.length > 1) {
// return (
// accounts
// .map((a) => a.accountNum)
// .reduce((a, b) => Math.max(a, b), -Infinity) + 1
// )
// } else if (accounts.length === 1) {
// return accounts[0].accountNum + 1
// }
// return 0
// }
2023-09-12 17:37:41 -07:00
2023-09-20 18:33:18 -07:00
function StakeForm({ token: selectedToken }: StakeFormProps) {
2023-09-12 17:37:41 -07:00
const { t } = useTranslation(['common', 'account'])
const [inputAmount, setInputAmount] = useState('')
2023-09-26 06:15:36 -07:00
const submitting = mangoStore((s) => s.submittingBoost)
2023-09-12 17:37:41 -07:00
const [leverage, setLeverage] = useState(1)
const [refreshingWalletTokens, setRefreshingWalletTokens] = useState(false)
const { maxSolDeposit } = useSolBalance()
const { usedTokens, totalTokens } = useMangoAccountAccounts()
const { group } = useMangoGroup()
2023-09-24 05:55:00 -07:00
const groupLoaded = mangoStore((s) => s.groupLoaded)
2023-09-20 18:33:18 -07:00
const {
borrowBankBorrowRate,
leveragedAPY,
estimatedNetAPY,
2024-02-22 06:12:37 -08:00
collateralFeeAPY
2023-09-20 18:33:18 -07:00
} = useBankRates(selectedToken, leverage)
2024-02-22 08:02:05 -08:00
const leverageMax = useLeverageMax(selectedToken) * 0.9 // Multiplied by 0.975 becuase you cant actually get to the end of the inifinite geometric series?
2023-09-12 17:37:41 -07:00
const stakeBank = useMemo(() => {
2023-09-14 21:24:29 -07:00
return group?.banksMapByName.get(selectedToken)?.[0]
2023-09-12 17:37:41 -07:00
}, [selectedToken, group])
const borrowBank = useMemo(() => {
2024-02-20 04:59:49 -08:00
return group?.banksMapByName.get('USDC')?.[0]
2023-09-12 17:37:41 -07:00
}, [group])
2024-02-20 04:59:49 -08:00
const liquidationPrice = useMemo(() => {
const borrowMaintLiabWeight = borrowBank?.maintLiabWeight
const stakeMaintAssetWeight = stakeBank?.maintAssetWeight
2024-02-21 17:05:33 -08:00
const price =
Number(stakeBank?.uiPrice) *
(Number(borrowMaintLiabWeight) / Number(stakeMaintAssetWeight)) *
(1 - 1 / leverage)
2024-02-20 04:59:49 -08:00
return price
}, [stakeBank, borrowBank, leverage])
2024-02-22 05:40:49 -08:00
2023-09-12 17:37:41 -07:00
const tokenPositionsFull = useMemo(() => {
if (!stakeBank || !usedTokens.length || !totalTokens.length) return false
const hasTokenPosition = usedTokens.find(
(token) => token.tokenIndex === stakeBank.tokenIndex,
)
return hasTokenPosition ? false : usedTokens.length >= totalTokens.length
}, [stakeBank, usedTokens, totalTokens])
const { connected, publicKey } = useWallet()
const walletTokens = mangoStore((s) => s.wallet.tokens)
const tokenMax = useMemo(() => {
return walletBalanceForToken(walletTokens, selectedToken)
}, [walletTokens, selectedToken])
const setMax = useCallback(() => {
const max = floorToDecimal(tokenMax.maxAmount, 6)
setInputAmount(max.toFixed())
}, [tokenMax])
const amountToBorrow = useMemo(() => {
2024-02-20 04:59:49 -08:00
const borrowPrice = borrowBank?.uiPrice
2023-09-12 17:37:41 -07:00
const stakePrice = stakeBank?.uiPrice
2024-02-20 04:59:49 -08:00
if (!borrowPrice || !stakePrice || !Number(inputAmount)) return 0
2024-02-21 17:05:33 -08:00
const borrowAmount =
stakeBank?.uiPrice * Number(inputAmount) * (leverage - 1)
2023-09-12 17:37:41 -07:00
return borrowAmount
}, [leverage, borrowBank, stakeBank, inputAmount])
2023-09-12 17:37:41 -07:00
2024-02-22 05:40:49 -08:00
2023-09-12 17:37:41 -07:00
const handleRefreshWalletBalances = useCallback(async () => {
if (!publicKey) return
const actions = mangoStore.getState().actions
setRefreshingWalletTokens(true)
await actions.fetchWalletTokens(publicKey)
setRefreshingWalletTokens(false)
}, [publicKey])
const handleDeposit = useCallback(async () => {
const client = mangoStore.getState().client
const group = mangoStore.getState().group
const actions = mangoStore.getState().actions
2023-10-01 21:06:19 -07:00
// const mangoAccounts = mangoStore.getState().mangoAccounts
2023-09-12 17:37:41 -07:00
const mangoAccount = mangoStore.getState().mangoAccount.current
2024-02-21 17:05:33 -08:00
2023-09-12 17:37:41 -07:00
if (!group || !stakeBank || !publicKey) return
2023-09-26 06:15:36 -07:00
set((state) => {
state.submittingBoost = true
})
2023-10-09 22:43:03 -07:00
const tokenNum = STAKEABLE_TOKENS_DATA.find(
(t) => t.name.toLowerCase() === stakeBank.name.toLowerCase(),
)?.id
2023-09-12 17:37:41 -07:00
try {
2023-10-01 21:06:19 -07:00
// const newAccountNum = getNextAccountNumber(mangoAccounts)
2023-11-12 12:55:49 -08:00
notify({
title: 'Building transaction. This may take a moment.',
type: 'info',
})
2023-09-12 17:37:41 -07:00
const { signature: tx, slot } = await stakeAndCreate(
client,
group,
mangoAccount,
amountToBorrow,
2023-09-12 17:37:41 -07:00
stakeBank.mint,
parseFloat(inputAmount),
2023-11-10 07:55:12 -08:00
tokenNum || 0,
2023-09-12 17:37:41 -07:00
)
notify({
title: 'Transaction confirmed',
type: 'success',
txid: tx,
})
2023-09-26 06:15:36 -07:00
set((state) => {
state.submittingBoost = false
})
2023-09-12 20:59:43 -07:00
setInputAmount('')
2023-10-10 12:17:39 -07:00
await sleep(500)
if (!mangoAccount) {
await actions.fetchMangoAccounts(
(client.program.provider as AnchorProvider).wallet.publicKey,
)
}
await actions.reloadMangoAccount(slot)
await actions.fetchWalletTokens(publicKey)
2023-09-12 17:37:41 -07:00
} catch (e) {
console.error('Error depositing:', e)
2023-09-26 06:15:36 -07:00
set((state) => {
state.submittingBoost = false
})
2023-09-12 17:37:41 -07:00
if (!isMangoError(e)) return
notify({
title: 'Transaction failed',
description: e.message,
txid: e?.txid,
type: 'error',
})
}
2023-09-20 18:33:18 -07:00
}, [stakeBank, publicKey, inputAmount, amountToBorrow])
2023-09-12 17:37:41 -07:00
const showInsufficientBalance =
tokenMax.maxAmount < Number(inputAmount) ||
2024-02-20 04:59:49 -08:00
(selectedToken === 'USDC' && maxSolDeposit <= 0)
2023-09-12 17:37:41 -07:00
2023-09-22 06:33:36 -07:00
const changeLeverage = useCallback((v: number) => {
setLeverage(v * 1)
2023-09-12 17:37:41 -07:00
}, [])
useEffect(() => {
const group = mangoStore.getState().group
set((state) => {
state.swap.outputBank = group?.banksMapByName.get(selectedToken)?.[0]
})
}, [selectedToken])
return (
<>
2023-09-26 06:15:36 -07:00
<div className="flex flex-col justify-between">
<div className="pb-8">
<SolBalanceWarnings
amount={inputAmount}
className="mb-4"
setAmount={setInputAmount}
selectedToken={selectedToken}
/>
<div className="grid grid-cols-2">
<div className="col-span-2 flex justify-between">
<Label text="Amount" />
<div className="mb-2 flex items-center space-x-2">
<MaxAmountButton
decimals={tokenMax.maxDecimals}
label={t('wallet-balance')}
onClick={setMax}
value={tokenMax.maxAmount}
/>
2023-11-08 16:52:12 -08:00
<Tooltip content="Refresh Balance">
2023-09-26 06:15:36 -07:00
<IconButton
className={refreshingWalletTokens ? 'animate-spin' : ''}
onClick={handleRefreshWalletBalances}
hideBg
>
<ArrowPathIcon className="h-5 w-5" />
</IconButton>
</Tooltip>
2023-09-12 17:37:41 -07:00
</div>
2023-09-26 06:15:36 -07:00
</div>
<div className="col-span-2">
<div className="relative">
<NumberFormat
name="amountIn"
id="amountIn"
inputMode="decimal"
thousandSeparator=","
allowNegative={false}
isNumericString={true}
decimalScale={6}
className={NUMBERFORMAT_CLASSES}
placeholder="0.00"
value={inputAmount}
onValueChange={(e: NumberFormatValues) => {
setInputAmount(
!Number.isNaN(Number(e.value)) ? e.value : '',
)
}}
isAllowed={withValueLimit}
/>
<div className="absolute left-4 top-1/2 -translate-y-1/2">
<TokenLogo bank={stakeBank} size={24} />
</div>
<div className="absolute right-4 top-1/2 -translate-y-1/2">
<span className="font-bold text-th-fgd-1">
{formatTokenSymbol(selectedToken)}
</span>
2023-09-14 06:18:39 -07:00
</div>
2023-09-12 17:37:41 -07:00
</div>
</div>
2023-09-26 06:15:36 -07:00
</div>
<div className="mt-4">
<div className="flex items-center justify-between">
<Label text="Leverage" />
<p className="mb-2 font-bold text-th-fgd-1">{leverage}x</p>
2023-09-12 17:37:41 -07:00
</div>
2023-09-26 06:15:36 -07:00
<LeverageSlider
leverageMax={leverageMax}
onChange={changeLeverage}
2023-09-28 15:43:28 -07:00
step={0.01}
2023-09-26 06:15:36 -07:00
/>
</div>
{stakeBank && borrowBank ? (
<div className="pt-8">
<Disclosure>
{({ open }) => (
<>
<Disclosure.Button
2024-02-21 17:05:33 -08:00
className={`w-full rounded-xl border-2 border-th-bkg-3 px-4 py-3 text-left focus:outline-none ${
open ? 'rounded-b-none border-b-0' : ''
}`}
2023-09-26 06:15:36 -07:00
>
<div className="flex items-center justify-between">
<p className="font-medium">Est. Net APY</p>
<div className="flex items-center space-x-2">
<span className="text-lg font-bold text-th-success">
{estimatedNetAPY >= 0
? '+'
: estimatedNetAPY === 0
2024-02-21 17:05:33 -08:00
? ''
: '-'}
2023-09-22 06:33:36 -07:00
<FormatNumericValue
2023-09-26 06:15:36 -07:00
value={estimatedNetAPY}
2023-09-22 06:33:36 -07:00
decimals={2}
/>
%
</span>
2023-09-26 06:15:36 -07:00
<ChevronDownIcon
2024-02-21 17:05:33 -08:00
className={`${
open ? 'rotate-180' : 'rotate-360'
} h-6 w-6 shrink-0 text-th-fgd-1`}
2023-09-26 06:15:36 -07:00
/>
2023-09-22 06:33:36 -07:00
</div>
2023-09-26 06:15:36 -07:00
</div>
</Disclosure.Button>
<Disclosure.Panel className="space-y-2 rounded-xl rounded-t-none border-2 border-t-0 border-th-bkg-3 px-4 pb-3">
<div className="flex justify-between">
<p className="text-th-fgd-4">
{formatTokenSymbol(selectedToken)} Leveraged APY
</p>
<span className="font-bold text-th-success">
{leveragedAPY > 0.01 ? '+' : ''}
<FormatNumericValue
value={leveragedAPY}
decimals={2}
/>
%
</span>
</div>
<div className="flex justify-between">
<p className="text-th-fgd-4">
2024-02-22 05:40:49 -08:00
{formatTokenSymbol(selectedToken)} Collateral Fee APY
2023-09-26 06:15:36 -07:00
</p>
<span
2024-02-21 17:05:33 -08:00
className={`font-bold ${
2024-02-22 05:40:49 -08:00
collateralFeeAPY > 0.01
? 'text-th-error'
2024-02-21 17:05:33 -08:00
: 'text-th-bkg-4'
}`}
2023-09-26 06:15:36 -07:00
>
2024-02-22 05:40:49 -08:00
{collateralFeeAPY > 0.01 ? '-' : ''}
2023-09-26 06:15:36 -07:00
<FormatNumericValue
2024-02-22 05:40:49 -08:00
value={collateralFeeAPY?.toString()}
2023-09-26 06:15:36 -07:00
decimals={2}
/>
%
</span>
</div>
{borrowBank ? (
<>
<div className="flex justify-between">
2024-02-22 06:12:37 -08:00
<p className="text-th-fgd-4">{`${borrowBank?.name} Borrow Rate`}</p>
2023-09-26 06:15:36 -07:00
<span
2024-02-21 17:05:33 -08:00
className={`font-bold ${
borrowBankBorrowRate > 0.01
? 'text-th-error'
: 'text-th-bkg-4'
}`}
2023-09-26 06:15:36 -07:00
>
-
<FormatNumericValue
value={borrowBankBorrowRate}
decimals={2}
/>
%
</span>
</div>
<div className="flex justify-between">
<p className="text-th-fgd-4">{`${borrowBank.name} Borrowed`}</p>
<span
2024-02-21 17:05:33 -08:00
className={`font-bold ${
amountToBorrow > 0.001
? 'text-th-fgd-1'
: 'text-th-bkg-4'
}`}
2023-09-26 06:15:36 -07:00
>
<FormatNumericValue
value={amountToBorrow}
decimals={3}
/>
<span className="font-body text-th-fgd-4">
{' '}
{borrowBank.name}
2023-09-22 06:33:36 -07:00
</span>
2023-09-26 06:15:36 -07:00
</span>
</div>
2024-02-20 04:59:49 -08:00
<div className="flex justify-between">
<p className="text-th-fgd-4">{`${stakeBank.name} Position`}</p>
<span
2024-02-21 17:05:33 -08:00
className={`font-bold ${
amountToBorrow > 0.001
? 'text-th-fgd-1'
: 'text-th-bkg-4'
}`}
2024-02-20 04:59:49 -08:00
>
<FormatNumericValue
value={leverage * Number(inputAmount)}
decimals={3}
/>
<span className="font-body text-th-fgd-4">
{' '}
2024-02-21 17:05:33 -08:00
{stakeBank.name}{' '}
2024-02-20 04:59:49 -08:00
</span>
<span className="font-body text-th-fgd-4">
{' '}
(
2024-02-21 17:05:33 -08:00
<FormatNumericValue
value={
leverage *
Number(inputAmount) *
stakeBank?.uiPrice
}
decimals={3}
/>{' '}
{borrowBank.name})
2024-02-20 04:59:49 -08:00
</span>
</span>
</div>
<div className="flex justify-between">
<p className="text-th-fgd-4">{`Liquidation Price`}</p>
<span
2024-02-21 17:05:33 -08:00
className={`font-bold ${
amountToBorrow > 0.001
? 'text-th-fgd-1'
: 'text-th-bkg-4'
}`}
2024-02-20 04:59:49 -08:00
>
<FormatNumericValue
value={liquidationPrice}
decimals={5}
/>
<span className="font-body text-th-fgd-4">
{' '}
{borrowBank.name}
</span>
</span>
</div>
2023-09-26 06:15:36 -07:00
</>
) : null}
</Disclosure.Panel>
</>
)}
</Disclosure>
</div>
) : !groupLoaded ? (
<div className="pt-8">
<SheenLoader className="flex flex-1 rounded-xl">
<div className="h-[56px] w-full bg-th-bkg-2" />
</SheenLoader>
</div>
2023-09-12 17:37:41 -07:00
) : null}
</div>
2023-09-26 06:15:36 -07:00
{connected ? (
<Button
onClick={handleDeposit}
2023-10-02 05:30:58 -07:00
className="w-full"
2023-09-26 06:15:36 -07:00
disabled={connected && (!inputAmount || showInsufficientBalance)}
size="large"
>
{submitting ? (
<Loading className="mr-2 h-5 w-5" />
) : showInsufficientBalance ? (
<div className="flex items-center">
2024-02-21 17:05:33 -08:00
<ExclamationCircleIcon className="icon-shadow mr-2 h-5 w-5 shrink-0" />
2023-09-26 06:15:36 -07:00
{t('swap:insufficient-balance', {
symbol: selectedToken,
})}
</div>
) : (
`Boost! ${inputAmount} ${formatTokenSymbol(selectedToken)}`
)}
</Button>
) : (
2023-10-02 05:30:58 -07:00
<SecondaryConnectButton className="w-full" isLarge />
2023-09-26 06:15:36 -07:00
)}
{tokenPositionsFull ? (
<InlineNotification
type="error"
desc={
<>
{t('error-token-positions-full')}{' '}
<Link href="/settings" shallow>
{t('manage')}
</Link>
</>
}
/>
) : null}
</div>
2023-09-12 17:37:41 -07:00
</>
)
}
2023-09-20 18:33:18 -07:00
export default StakeForm