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

poc #1820

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft

poc #1820

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
6 changes: 6 additions & 0 deletions playground/nextjs-app-router/components/demo/Swap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,12 @@ function SwapComponent() {
<SwapSettingsSlippageInput />
</SwapSettings>
<SwapAmountInput
classNames={{
inputContainer: 'bg-red-500',
tokenButton: 'bg-blue-500',
tokenDropdown: 'bg-green-500',
balanceContainer: 'bg-yellow-500',
}}
label="Sell"
swappableTokens={swappableTokens}
token={ethToken}
Expand Down
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.36.5",
"version": "0.36.6",
"type": "module",
"repository": "https://github.com/coinbase/onchainkit.git",
"license": "MIT",
Expand Down
10 changes: 5 additions & 5 deletions src/swap/components/Swap.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ describe('Swap Component', () => {
expect(title).toHaveTextContent('Test Swap');
});

it('should pass className to container div', () => {
render(<Swap className="custom-class">Test Swap</Swap>);
// it('should pass className to container div', () => {
// render(<Swap className="custom-class">Test Swap</Swap>);

const container = screen.getByTestId('ockSwap_Container');
expect(container).toHaveClass('custom-class');
});
// const container = screen.getByTestId('ockSwap_Container');
// expect(container).toHaveClass('custom-class');
// });
});
49 changes: 7 additions & 42 deletions src/swap/components/Swap.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,17 @@
'use client';
import { Children, useMemo } from 'react';
import { useIsMounted } from '../../core-react/internal/hooks/useIsMounted';
import { useTheme } from '../../core-react/internal/hooks/useTheme';
import { findComponent } from '../../core-react/internal/utils/findComponent';
import { background, border, cn, color, text } from '../../styles/theme';
import { FALLBACK_DEFAULT_MAX_SLIPPAGE } from '../constants';
import type { SwapReact } from '../types';
import { SwapAmountInput } from './SwapAmountInput';
import { SwapButton } from './SwapButton';
import { SwapMessage } from './SwapMessage';
import { SwapProvider } from './SwapProvider';
import { SwapSettings } from './SwapSettings';
import { SwapToast } from './SwapToast';
import { SwapToggleButton } from './SwapToggleButton';

export function Swap({
children,
config = {
maxSlippage: FALLBACK_DEFAULT_MAX_SLIPPAGE,
},
className,
classNames,
experimental = { useAggregator: false },
isSponsored = false,
onError,
Expand All @@ -29,27 +21,6 @@ export function Swap({
headerLeftContent,
}: 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
Expand All @@ -72,23 +43,17 @@ export function Swap({
border.radius,
color.foreground,
'flex w-[500px] flex-col px-6 pt-6 pb-4',
className,
classNames?.container,
)}
data-testid="ockSwap_Container"
>
<div className="mb-4 flex items-center justify-between">
<div>
{headerLeftContent}
<h3 className={cn(text.title3)} data-testid="ockSwap_Title">
{title}
</h3>
{swapSettings}
<h3 className={cn(text.title3)} data-testid="ockSwap_Title">
{title}
</h3>
</div>
{inputs[0]}
<div className="relative h-1">{toggleButton}</div>
{inputs[1]}
{swapButton}
{swapToast}
<div className="flex">{swapMessage}</div>
{children}
</div>
</SwapProvider>
);
Expand Down
45 changes: 27 additions & 18 deletions src/swap/components/SwapAmountInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,23 @@ import { formatAmount } from '../utils/formatAmount';
import { useSwapContext } from './SwapProvider';

export function SwapAmountInput({
className,
classNames,
delayMs = 1000,
label,
token,
type,
swappableTokens,
}: SwapAmountInputReact) {
const { address, to, from, handleAmountChange } = useSwapContext();
const { address, to, from, handleAmountChange, classNames: swapClassNames } = useSwapContext();

const componentStyles = {
inputContainer: swapClassNames?.inputContainer ?? classNames?.inputContainer,
input: swapClassNames?.input ?? classNames?.input,
tokenContainer: swapClassNames?.tokenContainer ?? classNames?.tokenContainer,
tokenButton: swapClassNames?.tokenButton ?? classNames?.tokenButton,
tokenDropdown: swapClassNames?.tokenDropdown ?? classNames?.tokenDropdown,
balanceContainer: swapClassNames?.balanceContainer ?? classNames?.balanceContainer,
};

const source = useValue(type === 'from' ? from : to);
const destination = useValue(type === 'from' ? to : from);
Expand Down Expand Up @@ -85,20 +94,21 @@ export function SwapAmountInput({
className={cn(
background.secondary,
border.radius,
'box-border flex h-[148px] w-full flex-col items-start p-4',
className,
'my-0.5 box-border flex h-[148px] w-full flex-col items-start p-4',
componentStyles.inputContainer,
)}
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">
<div className={cn('flex w-full items-center justify-between', componentStyles.tokenContainer)}>
<TextInput
className={cn(
'mr-2 w-full border-[none] bg-transparent font-display text-[2.5rem]',
'leading-none outline-none',
hasInsufficientBalance && address ? color.error : color.foreground,
componentStyles.input,
)}
placeholder="0.0"
delayMs={delayMs}
Expand All @@ -113,37 +123,36 @@ export function SwapAmountInput({
token={source.token}
setToken={handleSetToken}
options={sourceTokenOptions}
classNames={{
dropdown: componentStyles.tokenDropdown,
button: componentStyles.tokenButton
}}
/>
) : (
source.token && (
<TokenChip className={pressable.inverse} token={source.token} />
<TokenChip className={cn(pressable.inverse, componentStyles.tokenButton)} token={source.token} />
)
)}
</div>
<div className="mt-4 flex w-full justify-between">
<div className="flex items-center">
<span className={cn(text.label2, color.foregroundMuted)}>
<div className={cn('mt-4 flex w-full items-center justify-between', componentStyles.balanceContainer)}>
<span className={cn(text.label2, color.foregroundMuted, 'grow')}>
{formatUSD(source.amountUSD)}
</span>
</div>
<span className={cn(text.label2, color.foregroundMuted)}>{''}</span>
<div className="flex items-center">
{source.balance && (
<span
className={cn(text.label2, color.foregroundMuted)}
>{`Balance: ${getRoundedAmount(source.balance, 8)}`}</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>
</div>
</div>
);
Expand Down
6 changes: 3 additions & 3 deletions src/swap/components/SwapButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ 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 +33,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 +55,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
2 changes: 2 additions & 0 deletions src/swap/components/SwapProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export function useSwapContext() {

export function SwapProvider({
children,
classNames,
config = {
maxSlippage: FALLBACK_DEFAULT_MAX_SLIPPAGE,
},
Expand Down Expand Up @@ -364,6 +365,7 @@ export function SwapProvider({

const value = useValue({
address,
classNames,
config,
from,
handleAmountChange,
Expand Down
2 changes: 1 addition & 1 deletion src/swap/components/SwapToggleButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function SwapToggleButton({ className }: SwapToggleButtonReact) {
className={cn(
pressable.alternate,
border.default,
'-translate-x-2/4 -translate-y-2/4 absolute top-2/4 left-2/4',
'-my-6 relative mx-auto',
'flex h-12 w-12 items-center justify-center',
'rounded-lg border-4 border-solid',
className,
Expand Down
11 changes: 8 additions & 3 deletions src/swap/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,9 @@ export type ProcessSwapTransactionParams = {
* Note: exported as public Type
*/
export type SwapAmountInputReact = {
className?: string; // Optional className override for top div element.
classNames?: Pick<SwapClassNames, 'inputContainer' | 'input' | 'tokenContainer' |'tokenButton' | 'tokenDropdown' | 'balanceContainer'>;
delayMs?: number; // The debounce delay in milliseconds
label: string; // Descriptive label for the input field
label: ReactNode; // Descriptive label for the input field
swappableTokens?: Token[]; // Swappable tokens
token?: Token; // Selected token
type: 'to' | 'from'; // Identifies if component is for toToken or fromToken
Expand All @@ -202,6 +202,7 @@ export type SwapAPIResponse = {
*/
export type SwapButtonReact = {
className?: string; // Optional className override for top div element.
label?: ReactNode; // Label for the swap button
disabled?: boolean; // Disables swap button
};

Expand All @@ -213,6 +214,7 @@ export type SwapContextType = {
address?: Address; // Used to check if user is connected in SwapButton
config: SwapConfig;
from: SwapUnit;
classNames?: SwapClassNames;
lifecycleStatus: LifecycleStatus;
handleAmountChange: (
t: 'from' | 'to',
Expand Down Expand Up @@ -274,8 +276,11 @@ export type SwapParams = {
to: Token;
};

type SwapClassNames = Partial<Record<'container' | 'inputContainer' | 'input' | 'tokenContainer' | 'tokenButton' | 'tokenDropdown' | 'balanceContainer', string>>;

export type SwapProviderReact = {
children: React.ReactNode;
classNames?: SwapClassNames;
config?: {
maxSlippage: number; // Maximum acceptable slippage for a swap. (default: 10) This is as a percent, not basis points
};
Expand All @@ -293,7 +298,7 @@ export type SwapProviderReact = {
*/
export type SwapReact = {
children: ReactNode;
className?: string; // Optional className override for top div element.
classNames?: SwapClassNames; // Optional className override for top div element.
config?: SwapConfig;
experimental?: {
useAggregator: boolean; // Whether to use a DEX aggregator. (default: true)
Expand Down
4 changes: 3 additions & 1 deletion src/token/components/TokenSelectDropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export function TokenSelectDropdown({
options,
setToken,
token,
classNames,
}: TokenSelectDropdownReact) {
const componentTheme = useTheme();

Expand Down Expand Up @@ -55,6 +56,7 @@ export function TokenSelectDropdown({
onClick={handleToggle}
isOpen={isOpen}
token={token}
className={classNames?.button}
/>
{isOpen && (
<div
Expand All @@ -70,7 +72,7 @@ export function TokenSelectDropdown({
<div className="overflow-y-auto bg-[#ffffff]">
{options.map((token) => (
<TokenRow
className={cn(background.inverse, 'px-4 py-2')}
className={cn(background.inverse, 'px-4 py-2', classNames?.dropdown)}
key={token.name + token.address}
token={token}
onClick={() => {
Expand Down
1 change: 1 addition & 0 deletions src/token/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export type TokenSelectDropdownReact = {
options: Token[]; // List of tokens
setToken: (token: Token) => void; // Token setter
token?: Token; // Selected token
classNames?: Partial<Record<'button' | 'dropdown', string>>;
};

/**
Expand Down
Loading