Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Custom slippage for switch widget #2071

Merged
merged 4 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 63 additions & 7 deletions src/components/transactions/Switch/SwitchModalContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,50 @@ interface SwitchModalContentProps {
addNewToken: (token: TokenInfoWithBalance) => Promise<void>;
}

enum ValidationSeverity {
ERROR = 'error',
WARNING = 'warning',
}

export interface ValidationData {
message: string;
severity: ValidationSeverity;
}

const validateSlippage = (slippage: string): ValidationData | undefined => {
try {
const numberSlippage = Number(slippage);
if (Number.isNaN(numberSlippage))
return {
message: 'Invalid slippage',
severity: ValidationSeverity.ERROR,
};
if (numberSlippage > 30)
return {
message: 'Slippage must be lower 30%',
severity: ValidationSeverity.ERROR,
};
if (numberSlippage < 0)
return {
message: 'Slippage must be positive',
severity: ValidationSeverity.ERROR,
};
if (numberSlippage > 10)
return {
message: 'High slippage',
severity: ValidationSeverity.WARNING,
};
if (numberSlippage < 0.1)
return {
message: 'Slippage lower than 0.1% may result in failed transactions',
severity: ValidationSeverity.WARNING,
};
return undefined;
} catch {
return { message: 'Invalid slippage', severity: ValidationSeverity.ERROR };
}
};

export const SwitchModalContent = ({
supportedNetworks,
selectedChainId,
Expand All @@ -49,7 +93,7 @@ export const SwitchModalContent = ({
tokens,
addNewToken,
}: SwitchModalContentProps) => {
const [slippage, setSlippage] = useState('0.001');
const [slippage, setSlippage] = useState('0.10');
const [inputAmount, setInputAmount] = useState('');
const [debounceInputAmount, setDebounceInputAmount] = useState('');
const { mainTxState: switchTxState, gasLimit, txError, setTxError } = useModalContext();
Expand All @@ -64,6 +108,13 @@ export const SwitchModalContent = ({

const isWrongNetwork = useIsWrongNetwork(selectedChainId);

const slippageValidation = validateSlippage(slippage);

const safeSlippage =
slippageValidation && slippageValidation.severity === ValidationSeverity.ERROR
? 0
: Number(slippage) / 100;

const handleInputChange = (value: string) => {
setTxError(undefined);
if (value === '-1') {
Expand Down Expand Up @@ -114,7 +165,7 @@ export const SwitchModalContent = ({
outIconUri={selectedOutputToken.logoURI}
outAmount={(
Number(normalize(sellRates.destAmount, sellRates.destDecimals)) *
(1 - Number(slippage))
(1 - safeSlippage)
).toString()}
/>
);
Expand Down Expand Up @@ -180,7 +231,11 @@ export const SwitchModalContent = ({
selectedNetwork={selectedChainId}
setSelectedNetwork={handleSelectedNetworkChange}
/>
<SwitchSlippageSelector slippage={slippage} setSlippage={setSlippage} />
<SwitchSlippageSelector
slippageValidation={slippageValidation}
slippage={slippage}
setSlippage={setSlippage}
/>
</Box>
{!selectedInputToken || !selectedOutputToken ? (
<CircularProgress />
Expand Down Expand Up @@ -259,7 +314,7 @@ export const SwitchModalContent = ({
variant="caption"
value={
Number(normalize(sellRates.destAmount, sellRates.destDecimals)) *
(1 - Number(slippage))
(1 - safeSlippage)
}
/>
</Row>
Expand All @@ -272,7 +327,7 @@ export const SwitchModalContent = ({
symbol="usd"
symbolsVariant="caption"
variant="caption"
value={Number(sellRates.destUSD) * (1 - Number(slippage))}
value={Number(sellRates.destUSD) * (1 - safeSlippage)}
/>
</Row>
</TxModalDetails>
Expand Down Expand Up @@ -300,11 +355,12 @@ export const SwitchModalContent = ({
outputToken={selectedOutputToken.address}
inputName={selectedInputToken.name}
outputName={selectedOutputToken.name}
slippage={slippage}
slippage={safeSlippage.toString()}
blocked={
!sellRates ||
Number(debounceInputAmount) > Number(selectedInputToken.balance) ||
!user
!user ||
slippageValidation?.severity === ValidationSeverity.ERROR
}
chainId={selectedChainId}
route={sellRates}
Expand Down
80 changes: 70 additions & 10 deletions src/components/transactions/Switch/SwitchSlippageSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { Trans } from '@lingui/macro';
import {
Box,
Button,
InputAdornment,
InputBase,
Menu,
SvgIcon,
ToggleButton,
Expand All @@ -11,16 +13,25 @@ import {
} from '@mui/material';
import { MouseEvent, useState } from 'react';
import { FormattedNumber } from 'src/components/primitives/FormattedNumber';
import { Warning } from 'src/components/primitives/Warning';

const DEFAULT_SLIPPAGE_OPTIONS = ['0.001', '0.005', '0.01'];
import { ValidationData } from './SwitchModalContent';

const DEFAULT_SLIPPAGE_OPTIONS = ['0.10', '0.50', '1.00'];

type SwitchSlippageSelectorProps = {
slippage: string;
setSlippage: (value: string) => void;
slippageValidation?: ValidationData;
};

export const SwitchSlippageSelector = ({ slippage, setSlippage }: SwitchSlippageSelectorProps) => {
export const SwitchSlippageSelector = ({
slippage,
setSlippage,
slippageValidation,
}: SwitchSlippageSelectorProps) => {
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>();
const [isCustomSlippage, setIsCustomSlippage] = useState(false);

const open = Boolean(anchorEl);

Expand All @@ -32,11 +43,24 @@ export const SwitchSlippageSelector = ({ slippage, setSlippage }: SwitchSlippage
setAnchorEl(null);
};

const handleCustomSlippageChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setSlippage(event.target.value);
setIsCustomSlippage(true);
};

const handlePresetSlippageChange = (value: string) => {
setSlippage(value);
setIsCustomSlippage(false);
};

return (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="caption" color="text.secondary">
<Trans>Slippage</Trans>
<Menu
sx={{
maxWidth: '330px',
}}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'right',
Expand All @@ -57,43 +81,79 @@ export const SwitchSlippageSelector = ({ slippage, setSlippage }: SwitchSlippage
<Typography variant="subheader2" mb={5}>
<Trans>Max slippage</Trans>
</Typography>
<Box sx={{ display: 'flex', alignItems: 'center' }}>
<Box sx={{ display: 'flex', alignItems: 'center', flexDirection: 'row', gap: '8px' }}>
<ToggleButtonGroup
sx={{ backgroundColor: 'background.surface', borderRadius: '6px', p: '2px' }}
sx={{
backgroundColor: 'background.surface',
borderRadius: '6px',
borderColor: 'background.surface',
}}
exclusive
onChange={(_, value) => setSlippage(value)}
onChange={(_, value) => handlePresetSlippageChange(value)}
>
{DEFAULT_SLIPPAGE_OPTIONS.map((option) => (
<ToggleButton
sx={{
borderRadius: 1,
py: 1,
px: 2,
borderColor: 'transparent',
backgroundColor: option === slippage ? 'background.paper' : 'transparent',
borderWidth: 2,
backgroundColor:
option === slippage && !isCustomSlippage ? 'background.paper' : 'transparent',
}}
value={option}
key={option}
>
<FormattedNumber
value={option}
percent
visibleDecimals={2}
symbol="%"
variant="subheader2"
color="primary.main"
symbolsColor="primary.main"
/>
</ToggleButton>
))}
</ToggleButtonGroup>
<InputBase
type="percent"
value={isCustomSlippage ? slippage : ''}
onChange={handleCustomSlippageChange}
placeholder="Custom"
endAdornment={
<InputAdornment position="end">
<Typography variant="caption" color="text.muted">
%
</Typography>
</InputAdornment>
}
sx={{
fontSize: '12px',
px: 2,
width: '120px',
border: 1,
borderWidth: '1px',
backgroundColor: 'background.surface',
borderColor: slippageValidation
? `${slippageValidation.severity}.main`
: 'background.surface',
borderRadius: '4px',
}}
/>
</Box>
{slippageValidation && (
<Warning sx={{ mb: 0, mt: 2 }} severity={slippageValidation.severity}>
{slippageValidation.message}
</Warning>
)}
</Menu>
</Typography>
<FormattedNumber
variant="caption"
color="text.primary"
color={slippageValidation ? `${slippageValidation.severity}.main` : 'text.primary'}
value={slippage}
visibleDecimals={2}
percent
symbol="%"
/>
<Button
id="switch-slippage-selector-button"
Expand Down
Loading