Skip to content

Commit

Permalink
added the calculation for health factor on the dashboard page
Browse files Browse the repository at this point in the history
  • Loading branch information
Dprof-in-tech committed Dec 14, 2024
1 parent d349a08 commit bc34191
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 3 deletions.
95 changes: 92 additions & 3 deletions frontend/src/pages/forms/Form.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import { ReactComponent as ETH } from '../../assets/icons/ethereum.svg';
import { ReactComponent as USDC } from '../../assets/icons/borrow_usdc.svg';
import { ReactComponent as STRK } from '../../assets/icons/strk.svg';
Expand All @@ -19,6 +19,28 @@ import { useCheckPosition } from 'hooks/useClosePosition';
import { useNavigate } from 'react-router-dom';
import { ActionModal } from 'components/ui/ActionModal';

// Token configuration
const TOKEN_CONFIG = {
ETH: {
id: 'ethereum',
collateralFactor: 0.8,
borrowFactor: 0.9,
decimals: 18
},
USDC: {
id: 'usd-coin',
collateralFactor: 0.85,
borrowFactor: 0.9,
decimals: 6
},
STRK: {
id: 'starknet',
collateralFactor: 0.75,
borrowFactor: 0.85,
decimals: 18
}
};

const Form = () => {
const navigate = useNavigate();
const { walletId, setWalletId } = useWalletStore();
Expand All @@ -29,11 +51,70 @@ const Form = () => {
const [loading, setLoading] = useState(false);
const [alertMessage, setAlertMessage] = useState('');
const [successful, setSuccessful] = useState(false);
const [tokenPrice, setTokenPrice] = useState(0);
const [healthFactor, setHealthFactor] = useState(0);

useLockBodyScroll(successful);
const [isClosePositionOpen, setClosePositionOpen] = useState(false);
const connectWalletMutation = useConnectWallet(setWalletId);
const { data: positionData, refetch: refetchPosition } = useCheckPosition();

// Fetch token price from CoinGecko
useEffect(() => {
const fetchTokenPrice = async () => {
try {
const tokenId = TOKEN_CONFIG[selectedToken].id;
const response = await fetch(
`https://api.coingecko.com/api/v3/simple/price?ids=${tokenId}&vs_currencies=usd`
);
const data = await response.json();
setTokenPrice(data[tokenId].usd);
} catch (error) {
console.error('Error fetching price:', error);
setTokenPrice(0);
}
};

if (selectedToken) {
fetchTokenPrice();
}
}, [selectedToken]);

// Calculate health factor whenever relevant values change
useEffect(() => {
const calculateHealthFactor = () => {
if (!tokenAmount || !selectedMultiplier || !tokenPrice) {
setHealthFactor(0);
return;
}

try {
const amount = parseFloat(tokenAmount);
const multiplier = parseFloat(selectedMultiplier);

const tokenConfig = TOKEN_CONFIG[selectedToken];

const collateralValue = amount * tokenPrice * tokenConfig.collateralFactor;

// Calculate borrowed amount (using multiplier)
const borrowedAmount = amount * tokenPrice * (multiplier - 1);

// Calculate debt value adjusted by borrow factor
const adjustedDebtValue = borrowedAmount / tokenConfig.borrowFactor;

// Calculate health factor
const healthFactorValue = collateralValue / adjustedDebtValue;

setHealthFactor(healthFactorValue.toFixed(6));
} catch (error) {
console.error('Error calculating health factor:', error);
setHealthFactor(0);
}
};

calculateHealthFactor();
}, [tokenAmount, selectedToken, selectedMultiplier, tokenPrice]);

const connectWalletHandler = () => {
if (!walletId) {
connectWalletMutation.mutate();
Expand Down Expand Up @@ -97,7 +178,7 @@ const Form = () => {
content={[
'You have already opened a position.',
'Please close active position to open a new one.',
'Click the Close Active Position button to continue.',
"Click the 'Close Active Position' button to continue.",
]}
cancelLabel="Cancel"
submitLabel="Close Active Position"
Expand Down Expand Up @@ -134,6 +215,14 @@ const Form = () => {
/>
</div>
<div>
<div className="form-health-factor">
<p>
Estimated Health Factor Level:
</p>
<p>
{healthFactor || 0}
</p>
</div>
<div className="form-button-container">
<Button variant="secondary" size="lg" type="submit">
Submit
Expand All @@ -146,4 +235,4 @@ const Form = () => {
);
};

export default Form;
export default Form;
12 changes: 12 additions & 0 deletions frontend/src/pages/forms/form.css
Original file line number Diff line number Diff line change
Expand Up @@ -522,3 +522,15 @@ input[type='number'].error {
font-size: 15px;
}
}

.form-health-factor{
display: flex;
flex-direction: row;
align-items: end;
justify-self: flex-end;
width: fit-content;
margin: 2px;
color: gray;
align-self: flex-end;
gap: 5px;
}

0 comments on commit bc34191

Please sign in to comment.