Skip to content

Commit

Permalink
✨ network: update auto switch network in collateral switch
Browse files Browse the repository at this point in the history
  • Loading branch information
franm91 committed May 10, 2024
1 parent 9f1c7e8 commit 4d3a056
Show file tree
Hide file tree
Showing 13 changed files with 56 additions and 57 deletions.
4 changes: 2 additions & 2 deletions components/ActiveStream/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ const WithdrawAndCancel: React.FC<{
fullWidth
variant="contained"
color="error"
mainAction={cancel}
onClick={cancel}
loading={loading}
data-testid={`vesting-stream-${tokenId}-cancel-submit`}
>
Expand Down Expand Up @@ -513,7 +513,7 @@ const ActiveStream: FC<ActiveStreamProps> = ({
<MainActionButton
fullWidth
variant="contained"
mainAction={handleWithdrawClick}
onClick={handleWithdrawClick}
loading={loading}
data-testid={`vesting-stream-${tokenId}-claim`}
>
Expand Down
2 changes: 1 addition & 1 deletion components/Allowances/RevokeButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const RevokeButton = ({
}, [erc20, opts, spenderAddress, update]);

return (
<MainActionButton variant="contained" loading={loading} fullWidth={fullWidth} mainAction={handleClick}>
<MainActionButton variant="contained" loading={loading} fullWidth={fullWidth} onClick={handleClick}>
{t('Revoke')}
</MainActionButton>
);
Expand Down
2 changes: 1 addition & 1 deletion components/GetEXA/SelectRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ const SelectRoute = () => {
<MainActionButton
disabled={(!route && !nativeSwap) || insufficientBalance}
variant="contained"
mainAction={handleSubmit}
onClick={handleSubmit}
loading={txStep === TXStep.CONFIRM_PENDING}
data-testid={nativeSwap ? 'get-exa-submit' : 'get-exa-review'}
>
Expand Down
2 changes: 1 addition & 1 deletion components/Leverager/Summary/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ const Summary = () => {
) : (
<MainActionButton
loading={isLoading || summaryLoading}
mainAction={requiresApproval ? approveLeverage : submit}
onClick={requiresApproval ? approveLeverage : submit}
fullWidth
variant="contained"
disabled={disabledConfirm || summaryLoading}
Expand Down
13 changes: 7 additions & 6 deletions components/OperationsModal/ModalSubmit/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React, { FC, MouseEvent, useCallback } from 'react';
import { LoadingButton } from '@mui/lab';
import { Button, CircularProgress, Typography } from '@mui/material';
import { Box } from '@mui/system';
import { useOperationContext } from 'contexts/OperationContext';
Expand Down Expand Up @@ -50,11 +49,12 @@ function ModalSubmit({ isLoading = false, disabled = false, submit, symbol, labe

const handleApproveClick = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
const text = (event.target as HTMLButtonElement).innerText;
track('Button Clicked', {
location: 'Operations Modal',
name: 'approve',
symbol,
text: event.currentTarget.innerText,
text,
});
handleSubmit();
},
Expand All @@ -63,11 +63,12 @@ function ModalSubmit({ isLoading = false, disabled = false, submit, symbol, labe

const handleSubmitClick = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
const text = (event.target as HTMLButtonElement).innerText;
track('Button Clicked', {
location: 'Operations Modal',
name: 'submit',
symbol,
text: event.currentTarget.innerText,
text,
});
handleSubmit();
},
Expand Down Expand Up @@ -101,7 +102,7 @@ function ModalSubmit({ isLoading = false, disabled = false, submit, symbol, labe
label={loadingButton.label}
/>
}
mainAction={handleApproveClick}
onClick={handleApproveClick}
color="primary"
variant="contained"
disabled={disabled}
Expand All @@ -113,7 +114,7 @@ function ModalSubmit({ isLoading = false, disabled = false, submit, symbol, labe
}

return (
<LoadingButton
<MainActionButton
fullWidth
loading={isLoading}
loadingIndicator={
Expand All @@ -134,7 +135,7 @@ function ModalSubmit({ isLoading = false, disabled = false, submit, symbol, labe
data-testid="modal-submit"
>
{errorButton ? errorButton : label}
</LoadingButton>
</MainActionButton>
);
}

Expand Down
8 changes: 5 additions & 3 deletions components/RewardsModal/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ const RewardsModal: FC<RewardsModalProps> = ({ isOpen, close }) => {
const submit = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
const to = showInput && isAddress(input) ? input : undefined;
const text = (event.target as HTMLButtonElement).innerText;
const assets = Object.entries(selected)
.filter(([, v]) => v)
.map(([symbol]) => symbol);
Expand All @@ -99,7 +100,7 @@ const RewardsModal: FC<RewardsModalProps> = ({ isOpen, close }) => {
name: 'claim',
location: 'Rewards',
to,
text: event.currentTarget.innerText,
text,
});
},
[claim, input, selected, showInput],
Expand Down Expand Up @@ -138,12 +139,13 @@ const RewardsModal: FC<RewardsModalProps> = ({ isOpen, close }) => {

const handleSecondaryClaim = useCallback(
(event: MouseEvent<HTMLButtonElement>) => {
const text = (event.target as HTMLButtonElement).innerText;
setShowInput(!showInput);
track('Button Clicked', {
href: '',
location: 'Rewards',
name: showInput ? 'claim to connected wallet' : 'claim to a different address',
text: event.currentTarget.innerText,
text,
});
},
[showInput],
Expand Down Expand Up @@ -295,7 +297,7 @@ const RewardsModal: FC<RewardsModalProps> = ({ isOpen, close }) => {
fullWidth
variant="contained"
disabled={disableSubmit}
mainAction={submit}
onClick={submit}
loading={loading}
>
{showInput ? `${t('Claim to')} ${differentAddress}` : t('Claim to connected wallet')}
Expand Down
2 changes: 1 addition & 1 deletion components/VestingInput/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@ function VestingInput({ refetch }: Props) {
fullWidth
variant="contained"
loading={isLoading}
mainAction={() => {
onClick={() => {
submit();
track('Button Clicked', {
location: 'Vesting',
Expand Down
13 changes: 2 additions & 11 deletions components/asset/MaturityPool/MaturityPoolsTable/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import { toPercentage } from 'utils/utils';
import numbers from 'config/numbers.json';
import useActionButton from 'hooks/useActionButton';
import useMaturityPools from 'hooks/useMaturityPools';
import { useTheme } from '@mui/material';
import { useTranslation } from 'react-i18next';
import getHourUTC2Local from 'utils/getHourUTC2Local';
import { track } from 'utils/mixpanel';
Expand All @@ -38,7 +37,6 @@ const HeadCell: FC<{ title: string; tooltipTitle?: string }> = ({ title, tooltip

const MaturityPoolsTable: FC<MaturityPoolsTableProps> = ({ symbol }) => {
const { t } = useTranslation();
const { palette } = useTheme();
const { handleActionClick } = useActionButton();
const { minAPRValue } = numbers;
const rows = useMaturityPools(symbol);
Expand Down Expand Up @@ -75,14 +73,7 @@ const MaturityPoolsTable: FC<MaturityPoolsTableProps> = ({ symbol }) => {
hover
>
<TableCell component="th" scope="row" width={120} sx={{ pl: 1.5 }}>
<Typography
variant="body1"
color={palette.mode === 'light' ? 'black' : 'white'}
fontWeight={600}
whiteSpace="nowrap"
>
{parseTimestamp(maturity)}
</Typography>
{parseTimestamp(maturity, "MMM DD, 'YY")}
</TableCell>
<TableCell align="left" width={80}>
${totalDeposited}
Expand All @@ -96,7 +87,7 @@ const MaturityPoolsTable: FC<MaturityPoolsTableProps> = ({ symbol }) => {
<TableCell align="left" width={50}>
{toPercentage(borrowAPR > minAPRValue ? borrowAPR : undefined)}
</TableCell>
<TableCell align="right" size="small" sx={{ cursor: 'default', pr: 1.5 }}>
<TableCell align="right" size="small" sx={{ cursor: 'default' }}>
<Button
data-testid={`fixed-${maturity}-deposit-${symbol}`}
disabled={depositAPR < minAPRValue}
Expand Down
18 changes: 9 additions & 9 deletions components/common/MainActionButton/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ import { useModal } from 'contexts/ModalContext';

interface MainActionButtonProps extends LoadingButtonProps {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mainAction?: (event?: any) => void;
onClick?: (event?: any) => void;
}

function MainActionButton({ mainAction, ...props }: MainActionButtonProps) {
function MainActionButton({ onClick, ...props }: MainActionButtonProps) {
const { t } = useTranslation();
const { isConnected, chain: displayNetwork, connect, impersonateActive, exitImpersonate } = useWeb3();
const { chain } = useNetwork();
Expand All @@ -25,22 +25,22 @@ function MainActionButton({ mainAction, ...props }: MainActionButtonProps) {
}, [close, exitImpersonate]);

const handleSwitchNetworkAndExecuteMainAction = useCallback(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async (event?: any) => {
async (event?: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
if (chain && chain.id !== displayNetwork.id && switchNetworkAsync) {
try {
const result = await switchNetworkAsync(displayNetwork.id);
if (result.id === displayNetwork.id) {
mainAction?.(event);

if (result.id === displayNetwork.id && onClick && event) {
onClick(event);
}
} catch (error) {
return;
}
} else {
mainAction?.(event);
} else if (onClick && event) {
onClick(event);
}
},
[chain, displayNetwork.id, switchNetworkAsync, mainAction],
[chain, displayNetwork.id, switchNetworkAsync, onClick],
);

if (impersonateActive) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React, { useCallback, useMemo, useState } from 'react';
import { CircularProgress, Tooltip, Typography } from '@mui/material';
import { useNetwork } from 'wagmi';
import { useNetwork, useSwitchNetwork } from 'wagmi';
import WAD from '@exactly/lib/esm/fixed-point-math/WAD';

import waitForTransaction from 'utils/waitForTransaction';
Expand All @@ -24,12 +24,10 @@ function SwitchCollateral({ symbol }: Props) {
const { marketAccount, refreshAccountData } = useAccountData(symbol);
const auditor = useAuditor();
const { chain } = useNetwork();
const {
chain: { id: displayNetworkId },
opts,
} = useWeb3();
const { chain: displayNetwork, opts } = useWeb3();

const healthFactor = useHealthFactor();
const { switchNetworkAsync } = useSwitchNetwork();

const [optimistic, setOptimistic] = useState<boolean | undefined>();
const checked = useMemo<boolean>(() => {
Expand All @@ -41,10 +39,6 @@ function SwitchCollateral({ symbol }: Props) {
const { disabled, disabledText } = useMemo<{ disabled: boolean; disabledText?: string }>(() => {
if (!marketAccount || !healthFactor) return { disabled: true };

if (chain && displayNetworkId !== chain.id) {
return { disabled: true, disabledText: t('You are connected to a different network') };
}

const { floatingBorrowAssets, fixedBorrowPositions, isCollateral, usdPrice, floatingDepositAssets, adjustFactor } =
marketAccount;

Expand All @@ -65,7 +59,7 @@ function SwitchCollateral({ symbol }: Props) {
}

return { disabled: false };
}, [marketAccount, healthFactor, chain, displayNetworkId, t]);
}, [marketAccount, healthFactor, t]);

const [loading, setLoading] = useState<boolean>(false);

Expand Down Expand Up @@ -98,6 +92,22 @@ function SwitchCollateral({ symbol }: Props) {
}
}, [marketAccount, auditor, opts, checked, symbol, refreshAccountData]);

const siwtchNetworkAndToggle = useCallback(async () => {
if (chain && chain.id !== displayNetwork.id && switchNetworkAsync) {
try {
const result = await switchNetworkAsync(displayNetwork.id);

if (result.id === displayNetwork.id) {
onToggle();
}
} catch (error) {
return;
}
} else {
onToggle();
}
}, [chain, displayNetwork.id, onToggle, switchNetworkAsync]);

if (loading) {
return (
<CircularProgress
Expand Down Expand Up @@ -130,7 +140,7 @@ function SwitchCollateral({ symbol }: Props) {
<span data-testid={`switch-collateral-${symbol}-wrapper`}>
<StyledSwitch
checked={checked}
onChange={onToggle}
onChange={siwtchNetworkAndToggle}
inputProps={{
'aria-label': t('Use this asset as collateral'),
'data-testid': `switch-collateral-${symbol}`,
Expand Down
2 changes: 1 addition & 1 deletion components/governance/Claimable/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ const Claim: FC<ClaimableProps & { refresh: () => void }> = ({ amount, proof, re
<MainActionButton
variant="contained"
fullWidth
mainAction={handleClick}
onClick={handleClick}
disabled={claimLoading || waitingClaim}
loading={claimLoading || waitingClaim}
>
Expand Down
4 changes: 2 additions & 2 deletions components/governance/Delegation/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ const Delegation = () => {
<MainActionButton
variant="contained"
fullWidth
mainAction={handleDelegateClick}
onClick={handleDelegateClick}
loading={submitLoading || waitingDelegate}
>
{t('Delegate votes')}
Expand All @@ -185,7 +185,7 @@ const Delegation = () => {
<MainActionButton
fullWidth
variant="outlined"
mainAction={writeClearDelegate}
onClick={writeClearDelegate}
loading={clearDelegateLoading || waitingClearDelegate || waitingDelegate}
>
{t('Revoke delegation')}
Expand Down
11 changes: 3 additions & 8 deletions pages/vesting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ const WithdrawAndCancel: React.FC<{
{t('Exit Read-Only Mode')}
</Button>
) : (
<MainActionButton loading={l} mainAction={cancel} color="error" variant="contained" fullWidth>
<MainActionButton loading={l} onClick={cancel} color="error" variant="contained" fullWidth>
{t('Withdraw and Cancel Stream')}
</MainActionButton>
)}
Expand Down Expand Up @@ -475,12 +475,7 @@ const Vesting: NextPage = () => {
{t('Exit Read-Only Mode')}
</Button>
) : (
<MainActionButton
loading={switchIsLoading}
mainAction={withdrawAll}
variant="contained"
fullWidth
>
<MainActionButton loading={switchIsLoading} onClick={withdrawAll} variant="contained" fullWidth>
{t('Withdraw All')}
</MainActionButton>
)}
Expand Down Expand Up @@ -554,7 +549,7 @@ const Vesting: NextPage = () => {
) : (
<MainActionButton
loading={loading}
mainAction={handleClaimAll}
onClick={handleClaimAll}
variant="contained"
fullWidth
data-testid="vesting-claim-all"
Expand Down

0 comments on commit 4d3a056

Please sign in to comment.