|
| 1 | +import { AmountRenderer } from '@/components/ui/amount-renderer'; |
| 2 | +import { Button } from '@/components/ui/button'; |
| 3 | +import { |
| 4 | + Dialog, |
| 5 | + DialogClose, |
| 6 | + DialogContent, |
| 7 | + DialogDescription, |
| 8 | + DialogFooter, |
| 9 | + DialogHeader, |
| 10 | + DialogTitle, |
| 11 | +} from '@/components/ui/dialog'; |
| 12 | +import { Item, ItemContent, ItemGroup } from '@/components/ui/item'; |
| 13 | +import { useAppForm } from '@/hooks/app-form'; |
| 14 | +import { sdk } from '@/lib/sdk'; |
| 15 | +import { useSlayerTx } from '@/lib/transactions'; |
| 16 | +import { shouldUseFullAmount } from '@/lib/utils'; |
| 17 | +import { validateDecimal } from '@/lib/validations'; |
| 18 | +import { Decimal } from '@sovryn/slayer-shared'; |
| 19 | +import { useMemo } from 'react'; |
| 20 | +import { useAccount } from 'wagmi'; |
| 21 | +import z from 'zod'; |
| 22 | +import { useStore } from 'zustand'; |
| 23 | +import { useStoreWithEqualityFn } from 'zustand/traditional'; |
| 24 | +import { MINIMUM_HEALTH_FACTOR } from '../../constants'; |
| 25 | +import { useMoneyMarketPositions } from '../../hooks/use-money-positions'; |
| 26 | +import { withdrawRequestStore } from '../../stores/withdraw-request.store'; |
| 27 | + |
| 28 | +const WithdrawDialogForm = () => { |
| 29 | + const { address } = useAccount(); |
| 30 | + |
| 31 | + const position = useStore(withdrawRequestStore, (state) => state.position!); |
| 32 | + |
| 33 | + const { data } = useMoneyMarketPositions({ |
| 34 | + pool: position.pool.id || 'default', |
| 35 | + address: address!, |
| 36 | + }); |
| 37 | + |
| 38 | + const { begin } = useSlayerTx({ |
| 39 | + onClosed: (ok: boolean) => { |
| 40 | + if (ok) { |
| 41 | + // close withdrawal dialog if tx was successful |
| 42 | + withdrawRequestStore.getState().reset(); |
| 43 | + } |
| 44 | + }, |
| 45 | + }); |
| 46 | + |
| 47 | + const maximumWithdrawAmount = useMemo(() => { |
| 48 | + const summary = data?.data?.summary; |
| 49 | + if (!summary) { |
| 50 | + return Decimal.ZERO; |
| 51 | + } |
| 52 | + |
| 53 | + // if user has no borrows or this position is not used as collateral, allow full withdrawal |
| 54 | + if (Decimal.from(summary.totalBorrowsUsd).eq(0) || !position.collateral) { |
| 55 | + return Decimal.from(position.supplied, position.token.decimals); |
| 56 | + } |
| 57 | + |
| 58 | + // min collateral at which we reach minimum collateral ratio |
| 59 | + const minCollateralUsd = Decimal.from(MINIMUM_HEALTH_FACTOR) |
| 60 | + .mul(summary.totalBorrowsUsd) |
| 61 | + .div(summary.currentLiquidationThreshold); |
| 62 | + const maxWithdrawUsd = Decimal.from(summary.supplyBalanceUsd).sub( |
| 63 | + minCollateralUsd, |
| 64 | + ); |
| 65 | + |
| 66 | + if (maxWithdrawUsd.lte(0)) { |
| 67 | + return Decimal.ZERO; |
| 68 | + } |
| 69 | + |
| 70 | + return maxWithdrawUsd.gt(position.suppliedUsd) |
| 71 | + ? Decimal.from(position.supplied, position.token.decimals) |
| 72 | + : maxWithdrawUsd.div(position.reserve.priceUsd); |
| 73 | + }, [ |
| 74 | + data, |
| 75 | + position.collateral, |
| 76 | + position.reserve.priceUsd, |
| 77 | + position.supplied, |
| 78 | + position.suppliedUsd, |
| 79 | + position.token.decimals, |
| 80 | + ]); |
| 81 | + |
| 82 | + const balance = useMemo( |
| 83 | + () => ({ |
| 84 | + value: maximumWithdrawAmount.toBigInt(), |
| 85 | + decimals: position.token.decimals, |
| 86 | + symbol: position.token.symbol, |
| 87 | + }), |
| 88 | + [position, maximumWithdrawAmount], |
| 89 | + ); |
| 90 | + |
| 91 | + const form = useAppForm({ |
| 92 | + defaultValues: { |
| 93 | + amount: '', |
| 94 | + }, |
| 95 | + validators: { |
| 96 | + onChange: z.object({ |
| 97 | + amount: validateDecimal({ |
| 98 | + min: 1n, |
| 99 | + max: balance.value ?? undefined, |
| 100 | + }), |
| 101 | + }), |
| 102 | + }, |
| 103 | + onSubmit: ({ value }) => { |
| 104 | + begin(() => |
| 105 | + sdk.moneyMarket.withdraw( |
| 106 | + { |
| 107 | + ...position.reserve, |
| 108 | + pool: position.pool, |
| 109 | + token: position.token, |
| 110 | + }, |
| 111 | + value.amount, |
| 112 | + // if position can be withdrawn in full and user entered near full amount, use full withdrawal to avoid dust issues |
| 113 | + maximumWithdrawAmount.eq(position.supplied) && |
| 114 | + shouldUseFullAmount(value.amount, position.supplied), |
| 115 | + { |
| 116 | + account: address!, |
| 117 | + }, |
| 118 | + ), |
| 119 | + ); |
| 120 | + }, |
| 121 | + onSubmitInvalid(props) { |
| 122 | + console.log('Withdraw request submission invalid:', props); |
| 123 | + }, |
| 124 | + onSubmitMeta() { |
| 125 | + console.log('Withdraw request submission meta:', form); |
| 126 | + }, |
| 127 | + }); |
| 128 | + |
| 129 | + const handleSubmit = (e: React.FormEvent) => { |
| 130 | + e.preventDefault(); |
| 131 | + e.stopPropagation(); |
| 132 | + form.handleSubmit(); |
| 133 | + }; |
| 134 | + |
| 135 | + const handleEscapes = (e: Event) => { |
| 136 | + // withdrawRequestStore.getState().reset(); |
| 137 | + e.preventDefault(); |
| 138 | + }; |
| 139 | + |
| 140 | + const calculateRemainingSupply = (withdrawAmount: string) => { |
| 141 | + const amount = Decimal.from(withdrawAmount || '0', position.token.decimals); |
| 142 | + const current = Decimal.from(position.supplied, position.token.decimals); |
| 143 | + if (amount.gt(current)) { |
| 144 | + return Decimal.ZERO.toString(); |
| 145 | + } |
| 146 | + return Decimal.from(position.supplied, position.token.decimals) |
| 147 | + .sub(withdrawAmount || '0') |
| 148 | + .toString(); |
| 149 | + }; |
| 150 | + |
| 151 | + return ( |
| 152 | + <form onSubmit={handleSubmit} id={form.formId}> |
| 153 | + <DialogContent |
| 154 | + onInteractOutside={handleEscapes} |
| 155 | + onEscapeKeyDown={handleEscapes} |
| 156 | + onOpenAutoFocus={(e) => e.preventDefault()} |
| 157 | + > |
| 158 | + <DialogHeader> |
| 159 | + <DialogTitle>Withdraw Asset</DialogTitle> |
| 160 | + <DialogDescription className="sr-only"> |
| 161 | + Withdraw your supplied assets from the money market. |
| 162 | + </DialogDescription> |
| 163 | + </DialogHeader> |
| 164 | + <form.AppField name="amount"> |
| 165 | + {(field) => ( |
| 166 | + <field.AmountField |
| 167 | + label="Amount to Withdraw" |
| 168 | + placeholder="Amount" |
| 169 | + balance={balance} |
| 170 | + addonRight={balance.symbol} |
| 171 | + /> |
| 172 | + )} |
| 173 | + </form.AppField> |
| 174 | + |
| 175 | + <form.Subscribe selector={(state) => state.values.amount}> |
| 176 | + {(withdrawAmount) => ( |
| 177 | + <ItemGroup> |
| 178 | + <Item size="sm" className="py-1"> |
| 179 | + <ItemContent>Remaining supply:</ItemContent> |
| 180 | + <ItemContent> |
| 181 | + <AmountRenderer |
| 182 | + value={calculateRemainingSupply(withdrawAmount)} |
| 183 | + suffix={position.token.symbol} |
| 184 | + showApproxSign |
| 185 | + /> |
| 186 | + </ItemContent> |
| 187 | + </Item> |
| 188 | + </ItemGroup> |
| 189 | + )} |
| 190 | + </form.Subscribe> |
| 191 | + |
| 192 | + <DialogFooter> |
| 193 | + <DialogClose asChild> |
| 194 | + <Button variant="secondary" type="button"> |
| 195 | + Close |
| 196 | + </Button> |
| 197 | + </DialogClose> |
| 198 | + <form.AppForm> |
| 199 | + <form.SubscribeButton label="Withdraw" /> |
| 200 | + </form.AppForm> |
| 201 | + </DialogFooter> |
| 202 | + </DialogContent> |
| 203 | + </form> |
| 204 | + ); |
| 205 | +}; |
| 206 | + |
| 207 | +export const WithdrawDialog = () => { |
| 208 | + const isOpen = useStoreWithEqualityFn( |
| 209 | + withdrawRequestStore, |
| 210 | + (state) => state.position !== null, |
| 211 | + ); |
| 212 | + |
| 213 | + const handleClose = (open: boolean) => { |
| 214 | + if (!open) { |
| 215 | + withdrawRequestStore.getState().reset(); |
| 216 | + } |
| 217 | + }; |
| 218 | + |
| 219 | + return ( |
| 220 | + <Dialog open={isOpen} onOpenChange={handleClose}> |
| 221 | + {isOpen && <WithdrawDialogForm />} |
| 222 | + </Dialog> |
| 223 | + ); |
| 224 | +}; |
0 commit comments