Skip to content

Commit

Permalink
Merge pull request #402 from fabrobles92/feat/refactoring_frontend
Browse files Browse the repository at this point in the history
Feature refactoring frontend
  • Loading branch information
djeck1432 authored Dec 19, 2024
2 parents e536de0 + 9d471f2 commit 883c19b
Show file tree
Hide file tree
Showing 21 changed files with 63 additions and 80 deletions.
1 change: 1 addition & 0 deletions frontend/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ module.exports = {
},
moduleNameMapper: {
'\\.svg$': '<rootDir>/test/__mocks__/svgMock.js',
'\\.css$': '<rootDir>/test/__mocks__/styleMock.js',
'^src/(.*)$': ['<rootDir>/src/$1'],
},
transformIgnorePatterns: [
Expand Down
5 changes: 2 additions & 3 deletions frontend/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,13 @@ import { getTelegramUserWalletId } from 'services/telegram';
import Documentation from 'pages/spotnet/documentation/Documentation';
import Withdraw from 'pages/vault/withdraw/Withdraw';
import { useWalletStore } from 'stores/useWalletStore';
import { Notifier } from 'components/Notifier/Notifier';
import { Notifier, notify } from 'components/Notifier/Notifier';
import { useConnectWallet } from 'hooks/useConnectWallet';
import OverviewPage from 'pages/spotnet/overview/Overview';
import { ActionModal } from 'components/ui/ActionModal';
import Stake from 'pages/vault/stake/Stake';
import { TELEGRAM_BOT_LINK } from 'utils/constants';
import { useCheckMobile } from 'hooks/useCheckMobile';
import { notifyError } from 'utils/notification';
import PositionHistory from 'pages/spotnet/position_history/PositionHistory';


Expand Down Expand Up @@ -72,7 +71,7 @@ function App() {
})
.catch((error) => {
console.error('Error getting Telegram user wallet ID:', error);
notifyError('Error loading wallet');
notify('Error loading wallet', "error");
window.Telegram.WebApp.ready();
});
}
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/LendingForm.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import React, { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { getTokenBalances, sendTransaction } from 'services/wallet';
import { notifyError } from 'utils/notification';
import { axiosInstance } from 'utils/axios';
import Button from 'components/ui/Button/Button';
import { useWalletStore } from 'stores /useWalletStore';
import { notify } from './Notifier/Notifier';


const LendingForm = () => {
Expand All @@ -29,7 +29,7 @@ const navigate = useNavigate();
setBalances(tokenBalances);
} catch (error) {
console.error('Failed to fetch balances:', error);
notifyError('Failed to fetch token balances. Please try again.');
notify('Failed to fetch token balances. Please try again.', "error");
}
}, [walletId]);

Expand Down
3 changes: 1 addition & 2 deletions frontend/src/components/MultiplierSelector.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import './multiplier.css';
const MultiplierSelector = ({ setSelectedMultiplier, selectedToken }) => {
const minMultiplier = 1.1;

const { data, isLoading, error } = useMaxMultiplier();
const { data, isLoading } = useMaxMultiplier();
const [actualValue, setActualValue] = useState(minMultiplier);
const sliderRef = useRef(null);
const isDragging = useRef(false);
Expand Down Expand Up @@ -104,7 +104,6 @@ const MultiplierSelector = ({ setSelectedMultiplier, selectedToken }) => {
}, [maxMultiplier, actualValue, setSelectedMultiplier]);

if (isLoading) return <div className="slider-skeleton">Loading multiplier data...</div>;
if (error) return <div className="error-message">Error loading multiplier data: {error.message}</div>;

return (
<div className="multiplier-card">
Expand Down
19 changes: 16 additions & 3 deletions frontend/src/components/Notifier/Notifier.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,27 @@ import React from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

const notify = (message) => toast(message);
const defaultStyles = {
success: { backgroundColor: 'green', color: 'white' },
error: { backgroundColor: 'red', color: 'white' },
warning: { backgroundColor: 'orange', color: 'white' },
info: { backgroundColor: 'blue', color: 'white' },
};

const ToastWithLink = (message, link, linkMessage) => (
<div>
<span>{message}</span> <a target='_blank' href={link}>{linkMessage}</a>
</div>
);

const notify = (message, type='info', autoClose=3000) => toast(message, { type, autoClose, style: defaultStyles[type] || defaultStyles.info });

const Notifier = () => {
return (
<div>
<ToastContainer />
<ToastContainer position='top-center' />
</div>
);
};

export { Notifier, notify };
export { Notifier, notify, ToastWithLink};
3 changes: 2 additions & 1 deletion frontend/src/components/SlideBarFour.jsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useState, useCallback, useMemo } from 'react';
import { useMaxMultiplier } from 'hooks/useMaxMultiplier';
import './slider-three.css';
import { notify } from 'components/Notifier/Notifier';

const StepSlider = ({ min = 0, max = 10, step = 1, defaultValue = 1, setSelectedMultiplier, selectedToken }) => {
const { data, isLoading, error } = useMaxMultiplier();
Expand Down Expand Up @@ -34,7 +35,7 @@ const StepSlider = ({ min = 0, max = 10, step = 1, defaultValue = 1, setSelected
}, [value, maxMultiplier, TOTAL_MARKS]);

if (isLoading) return <div className="slider-skeleton">Loading multiplier data...</div>;
if (error) return <div className="error-message">Error loading multiplier data: {error.message}</div>;
if (error) return notify(error.message, 'error');

const currentMark = getCurrentMark();

Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/WalletSection.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ const WalletSection = ({ onConnectWallet, onLogout }) => {
onLogout();
}}
>
Log out
Disconnect
</button>
</div>
)}
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/collateral/Collateral.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ function Collateral({ data, startSum, currentSum, getCurrentSumColor }) {
<span className="currency-name">{data[0]?.currencyName || 'N/A'}</span>
</div>
<span>
<span className="balance-label">Balance: </span>
<span className="balance-label">Position Balance: </span>
<span className="balance-value">{data[0]?.balance ? Number(data[0].balance).toFixed(8) : '0.00'}</span>
</span>
<span>
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/hooks/useClosePosition.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useMutation, useQuery } from '@tanstack/react-query';
import { axiosInstance } from 'utils/axios';
import { closePosition } from 'services/transaction';
import { useWalletStore } from 'stores/useWalletStore';
import { notify } from 'components/Notifier/Notifier';

export const useClosePosition = () => {
const { walletId } = useWalletStore();
Expand All @@ -18,6 +19,7 @@ export const useClosePosition = () => {
},
onError: (error) => {
console.error('Error during closePositionEvent', error);
notify(`Error during closePositionEvent: ${error.message}`, 'error')
},
});
};
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/hooks/useConnectWallet.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useMutation } from '@tanstack/react-query';
import { notify } from 'components/Notifier/Notifier';
import { connectWallet, checkForCRMToken } from 'services/wallet';
import { notifyError } from 'utils/notification';

export const useConnectWallet = (setWalletId) => {
return useMutation({
Expand All @@ -22,7 +22,7 @@ export const useConnectWallet = (setWalletId) => {
},
onError: (error) => {
console.error('Wallet connection failed:', error);
notifyError('Failed to connect wallet. Please try again.');
notify('Failed to connect wallet. Please try again.', "error");
},
});
};
6 changes: 4 additions & 2 deletions frontend/src/hooks/useMaxMultiplier.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
import { useQuery } from '@tanstack/react-query';
import { ONE_HOUR_IN_MILLISECONDS } from '../utils/constants';
import { axiosInstance } from 'utils/axios';
import { notify } from 'components/Notifier/Notifier';

export const useMaxMultiplier = () => {
const { data, isPending, error } = useQuery({
const { data, isPending } = useQuery({
queryKey: ['max-multiplier'],
queryFn: async () => {
const response = await axiosInstance.get(`/api/get-multipliers`);
return response.data.multipliers;
},
staleTime: ONE_HOUR_IN_MILLISECONDS,
refetchInterval: ONE_HOUR_IN_MILLISECONDS,
onError: (error) => notify(`Error using multiplier: ${error.message}`, 'error')
});

return { data, isLoading: isPending, error };
return { data, isLoading: isPending };
};
6 changes: 3 additions & 3 deletions frontend/src/hooks/useTelegramNotification.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useMutation } from "@tanstack/react-query";
import { subscribeToNotification, generateTelegramLink } from "services/telegram";
import { notifyError, notifySuccess } from "utils/notification";
import { notify } from "components/Notifier/Notifier";

const useTelegramNotification = () => {
const mutation = useMutation({
Expand All @@ -14,10 +14,10 @@ const useTelegramNotification = () => {
return await subscribeToNotification(telegramId, walletId);
},
onSuccess: () => {
notifySuccess("Subscribed to notifications successfully!");
notify("Subscribed to notifications successfully!", "success");
},
onError: (error) => {
notifyError(error?.message || "Failed to subscribe. Please try again.");
notify(error?.message || "Failed to subscribe. Please try again.", "error");
},
});

Expand Down
17 changes: 3 additions & 14 deletions frontend/src/pages/forms/Form.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import BalanceCards from 'components/BalanceCards';
import MultiplierSelector from 'components/MultiplierSelector';
import { handleTransaction } from 'services/transaction';
import Spinner from 'components/spinner/Spinner';
import { ReactComponent as AlertHexagon } from 'assets/icons/alert_hexagon.svg';
import './form.css';
import { createPortal } from 'react-dom';
import useLockBodyScroll from 'hooks/useLockBodyScroll';
Expand All @@ -19,16 +18,15 @@ import { useCheckPosition } from 'hooks/useClosePosition';
import { useNavigate } from 'react-router-dom';
import { ActionModal } from 'components/ui/ActionModal';
import { useHealthFactor } from 'hooks/useHealthRatio';
import { notify } from 'components/Notifier/Notifier';

const Form = () => {
const navigate = useNavigate();
const { walletId, setWalletId } = useWalletStore();
const [tokenAmount, setTokenAmount] = useState('');
const [selectedToken, setSelectedToken] = useState('ETH');
const [selectedMultiplier, setSelectedMultiplier] = useState('');
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const [alertMessage, setAlertMessage] = useState('');
const [successful, setSuccessful] = useState(false);

useLockBodyScroll(successful);
Expand Down Expand Up @@ -70,19 +68,17 @@ const Form = () => {
}

if (tokenAmount === '' || selectedToken === '' || selectedMultiplier === '') {
setAlertMessage('Please fill the form');
notify("Please fill the form", 'error')
return;
}

setAlertMessage('');

const formData = {
wallet_id: connectedWalletId,
token_symbol: selectedToken,
amount: tokenAmount,
multiplier: selectedMultiplier,
};
await handleTransaction(connectedWalletId, formData, setError, setTokenAmount, setLoading, setSuccessful);
await handleTransaction(connectedWalletId, formData, setTokenAmount, setLoading, setSuccessful);
};

const handleCloseModal = () => {
Expand Down Expand Up @@ -117,11 +113,6 @@ const Form = () => {
<div className="form-title">
<h1>Please submit your leverage details</h1>
</div>
{alertMessage && (
<p className="error-message form-alert">
{alertMessage} <AlertHexagon className="form-alert-hex" />
</p>
)}
<label className="token-select">Select Token</label>
<TokenSelector selectedToken={selectedToken} setSelectedToken={setSelectedToken} />
<label>Select Multiplier</label>
Expand All @@ -132,13 +123,11 @@ const Form = () => {
/>
<div className="token-label">
<label className="token-amount">Token Amount</label>
{error && <p className="error-message">{error}</p>}
<input
type="number"
placeholder="Enter Token Amount"
value={tokenAmount}
onChange={(e) => setTokenAmount(e.target.value)}
className={error ? 'error' : ''}
/>
</div>
<div>
Expand Down
8 changes: 1 addition & 7 deletions frontend/src/pages/spotnet/dashboard/Dashboard.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import Button from 'components/ui/Button/Button';
import { useWalletStore } from 'stores/useWalletStore';
import { ActionModal } from 'components/ui/ActionModal';
import useTelegramNotification from 'hooks/useTelegramNotification';
import { ReactComponent as AlertHexagon } from 'assets/icons/alert_hexagon.svg';
import Borrow from 'components/borrow/Borrow';
import { ReactComponent as CollateralIcon } from 'assets/icons/collateral_dynamic.svg';
import Collateral from 'components/collateral/Collateral';
Expand All @@ -30,7 +29,7 @@ export default function Component({ telegramId }) {
data: { health_ratio: '1.5', current_sum: '0.05', start_sum: '0.04', borrowed: '10.0' },
isLoading: false,
};
const { mutate: closePositionEvent, isLoading: isClosing, error: closePositionError } = useClosePosition(walletId);
const { mutate: closePositionEvent, isLoading: isClosing } = useClosePosition(walletId);
const { data: positionData } = useCheckPosition();
const { subscribe } = useTelegramNotification();

Expand Down Expand Up @@ -189,11 +188,6 @@ export default function Component({ telegramId }) {
>
{isClosing ? 'Closing...' : 'Redeem'}
</Button>
{closePositionError && (
<div className="error-message">
Error: {closePositionError.message} <AlertHexagon className="form-alert-hex" />
</div>
)}
<Button variant="secondary" size="lg" className="dashboard-btn telegram" onClick={handleOpen}>
<TelegramIcon className="tab-icon" />
Enable telegram notification bot
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/pages/spotnet/dont_miss/DontMiss.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const DontMiss = () => {
if (walletId) {
navigate('/form');
} else {
notify('Please connect to your wallet');
notify('Please connect to your wallet', 'warning');
}
};

Expand Down
4 changes: 2 additions & 2 deletions frontend/src/pages/spotnet/home/Home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import StarMaker from '../../../components/StarMaker';
import { ReactComponent as Decoration } from 'assets/particles/deco.svg';
import { ReactComponent as Starknet } from 'assets/particles/starknet.svg';
import { ReactComponent as Rocket } from 'assets/icons/rocket.svg';
import { notifyWarning } from 'utils/notification';
import './home.css';
import { useWalletStore } from 'stores/useWalletStore';
import { notify } from 'components/Notifier/Notifier';


function Home() {
Expand All @@ -19,7 +19,7 @@ function Home() {
if (walletId) {
navigate('/form');
} else {
notifyWarning('Please connect to your wallet');
notify('Please connect to your wallet', "warning");
}
};

Expand Down
2 changes: 2 additions & 0 deletions frontend/src/services/contract.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { connect } from 'get-starknet';
import { getDeployContractData } from '../utils/constants';
import { axiosInstance } from '../utils/axios';
import { notify, ToastWithLink } from '../components/Notifier/Notifier';

export async function deployContract(walletId) {
try {
Expand Down Expand Up @@ -39,6 +40,7 @@ export async function checkAndDeployContract(walletId) {
const result = await deployContract(walletId);
const contractAddress = result.contractAddress;

notify(ToastWithLink("Contract Deployed Successfully", `https://starkscan.co/tx/${result.transactionHash}`, "Transaction ID"), "success")
console.log('Contract address:', contractAddress);

// Update the backend with transaction hash and wallet ID
Expand Down
Loading

0 comments on commit 883c19b

Please sign in to comment.