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

refactor: remove swap findChildren #2077

Merged
merged 2 commits into from
Mar 7, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion playground/nextjs-app-router/onchainkit/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@coinbase/onchainkit",
"version": "0.37.4",
"version": "0.37.5",
"type": "module",
"repository": "https://github.com/coinbase/onchainkit.git",
"license": "MIT",
Expand Down
76 changes: 75 additions & 1 deletion src/swap/components/Swap.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,52 @@ import { render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { Swap } from './Swap';

vi.mock('wagmi', async (importOriginal) => {
const actual = await importOriginal<typeof import('wagmi')>();
return {
...actual,
useAccount: vi.fn().mockReturnValue({
address: '0x0000000000000000000000000000000000000000' as `0x${string}`,
chainId: 1,
}),
useConfig: vi.fn(),
useSwitchChain: vi.fn(),
useWriteContract: vi.fn(),
};
});

vi.mock('@/internal/hooks/useBreakpoints', () => ({
useBreakpoints: vi.fn().mockReturnValue('md'),
}));

vi.mock('./SwapProvider', () => ({
SwapProvider: ({ children }: { children: React.ReactNode }) => (
<div data-testid="mock-SwapProvider">{children}</div>
),
useSwapContext: vi.fn(),
useSwapContext: vi.fn().mockReturnValue({
address: '0x0000000000000000000000000000000000000000' as `0x${string}`,
config: {
maxSlippage: 10,
},
from: {
amount: '100',
},
to: {
amount: '100',
},
lifecycleStatus: {
statusName: 'init',
statusData: {
isMissingRequiredField: true,
maxSlippage: 10,
},
},
handleAmountChange: vi.fn(),
handleSubmit: vi.fn(),
handleToggle: vi.fn(),
updateLifecycleStatus: vi.fn(),
isToastVisible: false,
}),
}));

vi.mock('@/internal/svg/closeSvg', () => ({
Expand Down Expand Up @@ -46,4 +87,37 @@ describe('Swap Component', () => {
const container = screen.getByTestId('ockSwap_Container');
expect(container).toHaveClass('custom-class');
});

it('should render children', () => {
render(
<Swap>
<div>Test Child</div>
</Swap>,
);

expect(screen.getByText('Test Child')).toBeInTheDocument();
});

it('should render children when to, from, and disabled are provided', () => {
const toToken = {
address: '0x0000000000000000000000000000000000000000' as `0x${string}`,
chainId: 1,
decimals: 18,
image: 'https://example.com/image.png',
name: 'toToken',
symbol: 'toToken',
};
const fromToken = {
address: '0x0000000000000000000000000000000000000001' as `0x${string}`,
chainId: 1,
decimals: 18,
image: 'https://example.com/image.png',
name: 'fromToken',
symbol: 'fromToken',
};
render(<Swap to={[toToken]} from={[fromToken]} disabled={true} />);

expect(screen.getByText('Buy')).toBeInTheDocument();
expect(screen.getByText('Sell')).toBeInTheDocument();
});
});
73 changes: 41 additions & 32 deletions src/swap/components/Swap.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
'use client';
import { Children, useMemo } from 'react';
import { useIsMounted } from '../../internal/hooks/useIsMounted';
import { useTheme } from '../../internal/hooks/useTheme';
import { findComponent } from '../../internal/utils/findComponent';
import { background, border, cn, color, text } from '../../styles/theme';
import { FALLBACK_DEFAULT_MAX_SLIPPAGE } from '../constants';
import type { SwapReact } from '../types';
Expand All @@ -14,12 +12,43 @@ import { SwapSettings } from './SwapSettings';
import { SwapToast } from './SwapToast';
import { SwapToggleButton } from './SwapToggleButton';

function SwapDefaultContent({
to,
from,
disabled,
}: Pick<SwapReact, 'to' | 'from' | 'disabled'>) {
return (
<>
<SwapSettings />
<SwapAmountInput
label="Sell"
swappableTokens={from}
token={from?.[0]}
type="from"
/>
<SwapToggleButton />
<SwapAmountInput
label="Buy"
swappableTokens={to}
token={to?.[0]}
type="to"
/>
<SwapButton disabled={disabled} />
<SwapMessage />
<SwapToast />
</>
);
}

export function Swap({
children,
config = {
maxSlippage: FALLBACK_DEFAULT_MAX_SLIPPAGE,
},
className,
disabled,
to,
from,
experimental = { useAggregator: false },
isSponsored = false,
onError,
Expand All @@ -30,32 +59,13 @@ export function Swap({
}: SwapReact) {
const componentTheme = useTheme();

const {
inputs,
toggleButton,
swapButton,
swapMessage,
swapSettings,
swapToast,
} = useMemo(() => {
const childrenArray = Children.toArray(children);

return {
inputs: childrenArray.filter(findComponent(SwapAmountInput)),
toggleButton: childrenArray.find(findComponent(SwapToggleButton)),
swapButton: childrenArray.find(findComponent(SwapButton)),
swapMessage: childrenArray.find(findComponent(SwapMessage)),
swapSettings: childrenArray.find(findComponent(SwapSettings)),
swapToast: childrenArray.find(findComponent(SwapToast)),
};
}, [children]);

const isMounted = useIsMounted();

// prevents SSR hydration issue
if (!isMounted) {
return null;
}

return (
<SwapProvider
config={config}
Expand All @@ -71,24 +81,23 @@ export function Swap({
background.default,
border.radius,
color.foreground,
'flex w-[500px] flex-col px-6 pt-6 pb-4',
'relative flex w-full max-w-[500px] flex-col px-6 pt-6 pb-4',
className,
)}
data-testid="ockSwap_Container"
>
<div className="mb-4 flex items-center justify-between">
<div className="absolute flex w-1/2 items-center justify-between">
{headerLeftContent}
<h3 className={cn(text.title3)} data-testid="ockSwap_Title">
<h3
className={cn(text.title3, 'text-center')}
data-testid="ockSwap_Title"
>
{title}
</h3>
{swapSettings}
</div>
{inputs[0]}
<div className="relative h-1">{toggleButton}</div>
{inputs[1]}
{swapButton}
{swapToast}
<div className="flex">{swapMessage}</div>
{children ?? (
<SwapDefaultContent to={to} from={from} disabled={disabled} />
)}
</div>
</SwapProvider>
);
Expand Down
41 changes: 26 additions & 15 deletions src/swap/components/SwapAmountInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,19 @@ export function SwapAmountInput({
className={cn(
background.secondary,
border.radius,
'box-border flex h-[148px] w-full flex-col items-start p-4',
'my-0.5 box-border flex h-[148px] w-full flex-col items-start p-4',
className,
)}
data-testid="ockSwapAmountInput_Container"
>
<div className="flex w-full items-center justify-between">
<span className={cn(text.label2, color.foregroundMuted)}>{label}</span>
<div
className={cn(
text.label2,
color.foregroundMuted,
'flex w-full items-center justify-between',
)}
>
{label}
</div>
<div className="flex w-full items-center justify-between">
<TextInput
Expand Down Expand Up @@ -139,27 +145,32 @@ export function SwapAmountInput({
)
)}
</div>
<div className="mt-4 flex w-full justify-between">
<div className="flex items-center">
<span className={cn(text.label2, color.foregroundMuted)}>
{formatUSD(source.amountUSD)}
</span>
<div className="mt-4 flex w-full items-center justify-between">
<div className={cn(text.label2, color.foregroundMuted)}>
{formatUSD(source.amountUSD)}
</div>
<span className={cn(text.label2, color.foregroundMuted)}>{''}</span>
<div className="flex items-center">
<div
className={cn(
text.label2,
color.foregroundMuted,
'flex grow items-center justify-end',
)}
>
{source.balance && (
<span
className={cn(text.label2, color.foregroundMuted)}
>{`Balance: ${getRoundedAmount(source.balance, 8)}`}</span>
<span>{`Balance: ${getRoundedAmount(source.balance, 8)}`}</span>
)}
{type === 'from' && address && (
<button
type="button"
className="flex cursor-pointer items-center justify-center px-2 py-1"
className={cn(
text.label1,
color.primary,
'flex cursor-pointer items-center justify-center px-2 py-1',
)}
data-testid="ockSwapAmountInput_MaxButton"
onClick={handleMaxButtonClick}
>
<span className={cn(text.label1, color.primary)}>Max</span>
Max
</button>
)}
</div>
Expand Down
10 changes: 7 additions & 3 deletions src/swap/components/SwapButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import { ConnectWallet } from '@/wallet/components/ConnectWallet';
import type { SwapButtonReact } from '../types';
import { useSwapContext } from './SwapProvider';

export function SwapButton({ className, disabled = false }: SwapButtonReact) {
export function SwapButton({
className,
label = 'Swap',
disabled = false,
}: SwapButtonReact) {
const {
address,
to,
Expand Down Expand Up @@ -33,7 +37,7 @@ export function SwapButton({ className, disabled = false }: SwapButtonReact) {

// prompt user to connect wallet
if (!isDisabled && !address) {
return <ConnectWallet className="mt-4 w-full" />;
return <ConnectWallet className={cn('mt-4 w-full', className)} />;
}

return (
Expand All @@ -55,7 +59,7 @@ export function SwapButton({ className, disabled = false }: SwapButtonReact) {
{isLoading ? (
<Spinner />
) : (
<span className={cn(text.headline, color.inverse)}>Swap</span>
<span className={cn(text.headline, color.inverse)}>{label}</span>
)}
</button>
);
Expand Down
42 changes: 7 additions & 35 deletions src/swap/components/SwapDefault.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
'use client';
import type { SwapDefaultReact } from '../types';
import { Swap } from './Swap';
import { SwapAmountInput } from './SwapAmountInput';
import { SwapButton } from './SwapButton';
import { SwapMessage } from './SwapMessage';
import { SwapSettings } from './SwapSettings';
import { SwapSettingsSlippageDescription } from './SwapSettingsSlippageDescription';
import { SwapSettingsSlippageInput } from './SwapSettingsSlippageInput';
import { SwapSettingsSlippageTitle } from './SwapSettingsSlippageTitle';
import { SwapToast } from './SwapToast';
import { SwapToggleButton } from './SwapToggleButton';

/**
* @deprecated Use the `Swap` component instead with no 'children' props.
*/
export function SwapDefault({
config,
className,
Expand All @@ -34,31 +28,9 @@ export function SwapDefault({
isSponsored={isSponsored}
title={title}
experimental={experimental}
>
<SwapSettings>
<SwapSettingsSlippageTitle>Max. slippage</SwapSettingsSlippageTitle>
<SwapSettingsSlippageDescription>
Your swap will revert if the prices change by more than the selected
percentage.
</SwapSettingsSlippageDescription>
<SwapSettingsSlippageInput />
</SwapSettings>
<SwapAmountInput
label="Sell"
swappableTokens={from}
token={from?.[0]}
type="from"
/>
<SwapToggleButton />
<SwapAmountInput
label="Buy"
swappableTokens={to}
token={to?.[0]}
type="to"
/>
<SwapButton disabled={disabled} />
<SwapMessage />
<SwapToast />
</Swap>
to={to}
from={from}
disabled={disabled}
/>
);
}
Loading