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

chore: Update SwapSettingsSlippageInput to use Config #1263

Merged
merged 6 commits into from
Sep 17, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
5 changes: 5 additions & 0 deletions .changeset/late-bottles-greet.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@coinbase/onchainkit': patch
---

-**chore**: updated `SwapSettingsSlippageInput` to use the input config defaultMaxSlippage value. By @cpcramer #1263.
1 change: 1 addition & 0 deletions src/swap/components/SwapProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ export function SwapProvider({

const value = useValue({
address,
config,
from,
handleAmountChange,
handleToggle,
Expand Down
83 changes: 61 additions & 22 deletions src/swap/components/SwapSettingsSlippageInput.test.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
import { fireEvent, render, screen } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { DEFAULT_MAX_SLIPPAGE } from '../constants';
import { SwapSettingsSlippageInput } from './SwapSettingsSlippageInput';

const mockSetLifecycleStatus = vi.fn();
let mockLifecycleStatus = {
statusName: 'init',
statusData: {
isMissingRequiredField: false,
maxSlippage: 3,
maxSlippage: DEFAULT_MAX_SLIPPAGE,
},
};

vi.mock('./SwapProvider', () => ({
useSwapContext: () => ({
updateLifecycleStatus: mockSetLifecycleStatus,
lifecycleStatus: mockLifecycleStatus,
config: { maxSlippage: DEFAULT_MAX_SLIPPAGE },
}),
}));

Expand All @@ -29,14 +31,16 @@ describe('SwapSettingsSlippageInput', () => {
statusName: 'init',
statusData: {
isMissingRequiredField: false,
maxSlippage: 3,
maxSlippage: DEFAULT_MAX_SLIPPAGE,
},
};
});

it('renders with default props', () => {
render(<SwapSettingsSlippageInput />);
expect(screen.getByRole('textbox')).toHaveValue('3');
expect(screen.getByRole('textbox')).toHaveValue(
DEFAULT_MAX_SLIPPAGE.toString(),
);
expect(screen.getByText('%')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Auto' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Custom' })).toBeInTheDocument();
Expand All @@ -58,11 +62,13 @@ describe('SwapSettingsSlippageInput', () => {
expect(screen.getByRole('textbox')).toHaveValue('1.5');
});

it('allows input changes in Custom mode', () => {
it('allows input changes in Custom mode but maintains default value', () => {
render(<SwapSettingsSlippageInput />);
fireEvent.click(screen.getByRole('button', { name: 'Custom' }));
fireEvent.change(screen.getByRole('textbox'), { target: { value: '2.5' } });
expect(screen.getByRole('textbox')).toHaveValue('2.5');
expect(screen.getByRole('textbox')).toHaveValue(
DEFAULT_MAX_SLIPPAGE.toString(),
);
expect(mockSetLifecycleStatus).toHaveBeenCalledWith({
statusName: 'slippageChange',
statusData: {
Expand All @@ -76,12 +82,19 @@ describe('SwapSettingsSlippageInput', () => {
expect(screen.getByRole('textbox')).toBeDisabled();
});

it('prevents invalid input', () => {
it('handles invalid input by maintaining default value', () => {
render(<SwapSettingsSlippageInput />);
fireEvent.click(screen.getByRole('button', { name: 'Custom' }));
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'abc' } });
expect(screen.getByRole('textbox')).toHaveValue('3');
expect(mockSetLifecycleStatus).not.toHaveBeenCalled();
expect(screen.getByRole('textbox')).toHaveValue(
DEFAULT_MAX_SLIPPAGE.toString(),
);
expect(mockSetLifecycleStatus).toHaveBeenCalledWith({
statusName: 'slippageChange',
statusData: {
maxSlippage: 0,
},
});
});

it('handles decimal input correctly', () => {
Expand All @@ -90,7 +103,9 @@ describe('SwapSettingsSlippageInput', () => {
fireEvent.change(screen.getByRole('textbox'), {
target: { value: '2.75' },
});
expect(screen.getByRole('textbox')).toHaveValue('2.75');
expect(screen.getByRole('textbox')).toHaveValue(
DEFAULT_MAX_SLIPPAGE.toString(),
);
expect(mockSetLifecycleStatus).toHaveBeenCalledWith({
statusName: 'slippageChange',
statusData: {
Expand Down Expand Up @@ -124,12 +139,19 @@ describe('SwapSettingsSlippageInput', () => {
);
});

it('handles empty input correctly', () => {
it('handles empty input by maintaining default value', () => {
render(<SwapSettingsSlippageInput />);
fireEvent.click(screen.getByRole('button', { name: 'Custom' }));
fireEvent.change(screen.getByRole('textbox'), { target: { value: '' } });
expect(screen.getByRole('textbox')).toHaveValue('0');
expect(mockSetLifecycleStatus).not.toHaveBeenCalled();
expect(screen.getByRole('textbox')).toHaveValue(
DEFAULT_MAX_SLIPPAGE.toString(),
);
expect(mockSetLifecycleStatus).toHaveBeenCalledWith({
statusName: 'slippageChange',
statusData: {
maxSlippage: 0,
},
});
});

it('uses lifecycleStatus maxSlippage when available', () => {
Expand Down Expand Up @@ -159,36 +181,53 @@ describe('SwapSettingsSlippageInput', () => {
expect(screen.getByRole('textbox')).not.toBeDisabled();
});

it('handles non-numeric input correctly', () => {
it('handles non-numeric input by maintaining default value', () => {
render(<SwapSettingsSlippageInput />);
fireEvent.click(screen.getByRole('button', { name: 'Custom' }));
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'abc' } });
expect(screen.getByRole('textbox')).toHaveValue('3');
expect(mockSetLifecycleStatus).not.toHaveBeenCalled();
expect(screen.getByRole('textbox')).toHaveValue(
DEFAULT_MAX_SLIPPAGE.toString(),
);
expect(mockSetLifecycleStatus).toHaveBeenCalledWith({
statusName: 'slippageChange',
statusData: {
maxSlippage: 0,
},
});
});

it('updates slippage when switching from Custom to Auto', () => {
render(<SwapSettingsSlippageInput />);
fireEvent.click(screen.getByRole('button', { name: 'Custom' }));
fireEvent.change(screen.getByRole('textbox'), { target: { value: '5' } });
fireEvent.click(screen.getByRole('button', { name: 'Auto' }));
expect(screen.getByRole('textbox')).toHaveValue('3');
expect(screen.getByRole('textbox')).toHaveValue(
DEFAULT_MAX_SLIPPAGE.toString(),
);
expect(mockSetLifecycleStatus).toHaveBeenLastCalledWith({
statusName: 'slippageChange',
statusData: {
maxSlippage: 3,
maxSlippage: DEFAULT_MAX_SLIPPAGE,
},
});
});

it('maintains custom value when in Custom mode', () => {
it('maintains default value when switching between Auto and Custom mode', () => {
render(<SwapSettingsSlippageInput />);
expect(screen.getByRole('textbox')).toHaveValue(
DEFAULT_MAX_SLIPPAGE.toString(),
);
fireEvent.click(screen.getByRole('button', { name: 'Custom' }));
expect(screen.getByRole('textbox')).toHaveValue(
DEFAULT_MAX_SLIPPAGE.toString(),
);
fireEvent.change(screen.getByRole('textbox'), { target: { value: '5' } });
expect(screen.getByRole('textbox')).toHaveValue('5');
expect(screen.getByRole('textbox')).toHaveValue(
DEFAULT_MAX_SLIPPAGE.toString(),
);
fireEvent.click(screen.getByRole('button', { name: 'Auto' }));
fireEvent.click(screen.getByRole('button', { name: 'Custom' }));
fireEvent.change(screen.getByRole('textbox'), { target: { value: '7' } });
expect(screen.getByRole('textbox')).toHaveValue('7');
expect(screen.getByRole('textbox')).toHaveValue(
DEFAULT_MAX_SLIPPAGE.toString(),
);
});
});
32 changes: 13 additions & 19 deletions src/swap/components/SwapSettingsSlippageInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,22 @@ const SLIPPAGE_SETTINGS = {
export function SwapSettingsSlippageInput({
className,
}: SwapSettingsSlippageInputReact) {
const { updateLifecycleStatus, lifecycleStatus } = useSwapContext();
const getMaxSlippage = useCallback(() => {
return lifecycleStatus.statusData.maxSlippage;
}, [lifecycleStatus.statusData]);
Comment on lines -16 to -18
Copy link
Contributor Author

@cpcramer cpcramer Sep 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the getMaxSlippage function. useCallback is not providing many performance benefits here. Likely it's even slower than accessing lifecycleStatus.statusData.maxSlippage directly

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice

const {
updateLifecycleStatus,
lifecycleStatus,
config: { maxSlippage: defaultMaxSlippage },
cpcramer marked this conversation as resolved.
Show resolved Hide resolved
} = useSwapContext();

// Set initial slippage values to match previous selection or default,
// ensuring consistency when dropdown is reopened
const [slippage, setSlippage] = useState(getMaxSlippage());
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not needed anymore

const [slippageSetting, setSlippageSetting] = useState(
getMaxSlippage() === DEFAULT_MAX_SLIPPAGE
lifecycleStatus.statusData.maxSlippage === defaultMaxSlippage
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok nice

? SLIPPAGE_SETTINGS.AUTO
: SLIPPAGE_SETTINGS.CUSTOM,
);

const updateSlippage = useCallback(
(newSlippage: number) => {
setSlippage(newSlippage);
updateLifecycleStatus({
statusName: 'slippageChange',
statusData: {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

only call slippageChange if newSlippage !== lifecycleStatus.statusData.maxSlippage

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated!

Expand All @@ -39,20 +38,15 @@ export function SwapSettingsSlippageInput({
[updateLifecycleStatus],
);

// Handles user input for custom slippage
// Parses the input and updates slippage if valid
// Handles user input for custom slippage.
// Parses the input and updates slippage state.
const handleSlippageChange = useCallback(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well done in updating the comments as well

(newSlippage: string) => {
// Empty '' when the input field is cleared.
if (newSlippage === '') {
setSlippage(0);
return;
}
const parsedSlippage = Number.parseFloat(newSlippage);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

parseFloat('2.') = 2 preventing you from entering decimals

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is a fast follow update. I belieeve we will need to update getSwapQuote and buildSwapTransaction as well - this is where number <> string conversation happens again

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, parseFloat(2.2) = 2.2, its just typing the interim step will remove the dot before you type the next number

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cpcramer in your update to getSwapQuote and buildSwapTransaction - can you prevent the APIs from calling when amount=0? seems to be an edge case fired off from the component occasionally

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yep!

const isValidNumber = !Number.isNaN(parsedSlippage);

const newSlippageNumber = Number.parseFloat(newSlippage);
if (!Number.isNaN(newSlippageNumber)) {
updateSlippage(newSlippageNumber);
}
// Update slippage to parsed value if valid, otherwise set to 0
updateSlippage(isValidNumber ? parsedSlippage : 0);
},
[updateSlippage],
);
Expand Down Expand Up @@ -119,7 +113,7 @@ export function SwapSettingsSlippageInput({
<input
id="slippage-input"
type="text"
value={slippage}
value={lifecycleStatus.statusData.maxSlippage}
onChange={(e) => handleSlippageChange(e.target.value)}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you onChange={handleSlippageChange} and handle the event in your callback react won't have to create a new function here on every render

Copy link
Contributor Author

@cpcramer cpcramer Sep 17, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very cool! Curious if we prefer that optimization over (in my opinion) code simplicity

Before:

  onChange={(e) => handleSlippageChange(e.target.value)}

  const handleSlippageChange = useCallback(
    (newSlippage: string) => {
      const parsedSlippage = Number.parseFloat(newSlippage);
      const isValidNumber = !Number.isNaN(parsedSlippage);

      // Update slippage to parsed value if valid, otherwise set to 0
      updateSlippage(isValidNumber ? parsedSlippage : 0);
    },
    [updateSlippage],
  );

After:

onChange={handleSlippageChange}

const handleSlippageChange = useCallback(
  (e: React.ChangeEvent<HTMLInputElement>) => {
    const newSlippage = e.target.value;
    const parsedSlippage = Number.parseFloat(newSlippage);
    const isValidNumber = !Number.isNaN(parsedSlippage);

    // Update slippage to parsed value if valid, otherwise set to 0
    updateSlippage(isValidNumber ? parsedSlippage : 0);
  },
  [updateSlippage],
);

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it makes sense for a handleChange callback to accept a changeEvent

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i agree with Adam here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated

disabled={slippageSetting === SLIPPAGE_SETTINGS.AUTO}
className={cn(
Expand Down
3 changes: 3 additions & 0 deletions src/swap/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,9 @@ export type SwapButtonReact = {

export type SwapContextType = {
address?: Address; // Used to check if user is connected in SwapButton
config: {
maxSlippage: number; // Maximum acceptable slippage for a swap. (default: 10) This is as a percent, not basis points
};
cpcramer marked this conversation as resolved.
Show resolved Hide resolved
from: SwapUnit;
lifecycleStatus: LifecycleStatus;
handleAmountChange: (
Expand Down
Loading