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: Add balance to SwapAmountInput #548

Merged
merged 7 commits into from
Jun 13, 2024
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
11 changes: 2 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,20 +68,13 @@
"packemon": [
{
"bundle": false,
"platform": [
"browser"
]
"platform": ["browser"]
}
],
"publishConfig": {
"access": "public"
},
"files": [
"esm/**/*",
"lib/**/*",
"src/",
"src/**/*"
],
"files": ["esm/**/*", "lib/**/*", "src/", "src/**/*"],
"main": "./esm/index.js",
"types": "./esm/index.d.ts",
"module": "./esm/index.js",
Expand Down
65 changes: 64 additions & 1 deletion src/swap/components/SwapAmountInput.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ jest.mock('../../token', () => ({
TokenChip: jest.fn(() => <div>TokenChip</div>),
}));

jest.mock('wagmi', () => {
return {
useBalance: jest.fn(),
};
});

const mockContextValue = {
fromAmount: '10',
setFromAmount: jest.fn(),
Expand All @@ -26,14 +32,21 @@ const mockContextValue = {

const mockToken: Token = {
name: 'ETH',
address: '',
address: '0x123456789',
symbol: 'ETH',
decimals: 18,
image:
'https://wallet-api-production.s3.amazonaws.com/uploads/tokens/eth_288.png',
chainId: 8453,
};

const mockBalance = {
decimals: 18,
formatted: '0.0002851826238227',
symbol: 'ETH',
value: 285182623822700n,
};

describe('SwapAmountInput', () => {
beforeEach(() => {
jest.clearAllMocks();
Expand All @@ -49,6 +62,56 @@ describe('SwapAmountInput', () => {
expect(screen.getByText('From')).toBeInTheDocument();
});

it('renders from token input with max button and balance', () => {
(require('wagmi').useBalance as jest.Mock).mockReturnValue({
data: mockBalance,
});

render(
<SwapContext.Provider value={mockContextValue}>
<SwapAmountInput label="From" token={mockToken} type="from" />
</SwapContext.Provider>,
);
expect(screen.getByText('Balance: 0.00028518')).toBeInTheDocument();
expect(
screen.getByTestId('ockSwapAmountInput_MaxButton'),
).toBeInTheDocument();
});

it('does not render max button for to token input', () => {
(require('wagmi').useBalance as jest.Mock).mockReturnValue({
data: mockBalance,
});

render(
<SwapContext.Provider value={mockContextValue}>
<SwapAmountInput label="From" token={mockToken} type="to" />
</SwapContext.Provider>,
);
expect(
screen.queryByTestId('ockSwapAmountInput_MaxButton'),
).not.toBeInTheDocument();
});

it('updates input value with balance amount on max button click', () => {
(require('wagmi').useBalance as jest.Mock).mockReturnValue({
data: mockBalance,
});

render(
<SwapContext.Provider value={mockContextValue}>
<SwapAmountInput label="From" token={mockToken} type="from" />
</SwapContext.Provider>,
);

const maxButton = screen.getByTestId('ockSwapAmountInput_MaxButton');
fireEvent.click(maxButton);

expect(mockContextValue.setFromAmount).toHaveBeenCalledWith(
'0.0002851826238227',
);
});

it('displays the correct amount when this type is "from"', () => {
render(
<SwapContext.Provider value={mockContextValue}>
Expand Down
39 changes: 38 additions & 1 deletion src/swap/components/SwapAmountInput.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { useCallback, useContext, useEffect, useMemo } from 'react';

import { isValidAmount } from '../utils';
import { getRoundedAmount, isValidAmount } from '../utils';
import { TokenChip } from '../../token';
import { cn } from '../../utils/cn';
import { SwapContext } from '../context';
import { useBalance } from 'wagmi';
import type { UseBalanceReturnType } from 'wagmi';
import type { SwapAmountInputReact } from '../types';

export function SwapAmountInput({ label, token, type }: SwapAmountInputReact) {
const {
address,
fromAmount,
setFromAmount,
setFromToken,
Expand Down Expand Up @@ -37,6 +40,17 @@ export function SwapAmountInput({ label, token, type }: SwapAmountInputReact) {
return setFromToken;
}, [type, setFromToken, setToToken]);

const balanceResponse: UseBalanceReturnType = useBalance({
Copy link
Contributor

Choose a reason for hiding this comment

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

Screenshot 2024-06-13 at 2 24 23 PM

think this might only work with eth

Copy link
Contributor

Choose a reason for hiding this comment

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

@abcrane123 let's refactor this later today. Thank you @kyhyco

address,
...(token?.address && { token: token.address }),
});

const roundedBalance = useMemo(() => {
if (balanceResponse?.data?.formatted && token?.address) {
return getRoundedAmount(balanceResponse?.data?.formatted, 8);
}
}, [balanceResponse?.data]);

const handleAmountChange = useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
if (isValidAmount(event.target.value)) {
Expand All @@ -46,6 +60,12 @@ export function SwapAmountInput({ label, token, type }: SwapAmountInputReact) {
[setAmount],
);

const handleMaxButtonClick = useCallback(() => {
if (balanceResponse?.data?.formatted) {
setAmount?.(balanceResponse?.data?.formatted);
}
}, [balanceResponse?.data, setAmount]);

useEffect(() => {
if (token) {
setToken(token);
Expand All @@ -62,9 +82,26 @@ export function SwapAmountInput({ label, token, type }: SwapAmountInputReact) {
>
<div className="flex w-full items-center justify-between">
<label className="font-semibold text-[#030712] text-sm">{label}</label>
{roundedBalance && (
<label className="text-sm font-normal text-gray-400">{`Balance: ${roundedBalance}`}</label>
)}
</div>
<div className="flex w-full items-center justify-between">
<TokenChip token={token} />
{type === 'from' && (
<button
className={cn(
'flex h-8 w-[58px] max-w-[200px] items-center rounded-[40px]',
'bg-gray-100 px-3 py-2 text-base font-medium',
'not-italic leading-6 text-gray-500',
)}
data-testid="ockSwapAmountInput_MaxButton"
disabled={roundedBalance === undefined}
onClick={handleMaxButtonClick}
>
Max
</button>
)}
</div>
<input
className="w-full border-[none] bg-transparent text-5xl text-[black]"
Expand Down
23 changes: 22 additions & 1 deletion src/swap/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { formatTokenAmount, isSwapError, isValidAmount } from './utils'; // Adjust the import path as needed
import {
formatTokenAmount,
getRoundedAmount,
isSwapError,
isValidAmount,
} from './utils'; // Adjust the import path as needed

describe('isValidAmount', () => {
it('should return true for an empty string', () => {
Expand Down Expand Up @@ -98,3 +103,19 @@ describe('formatTokenAmount', () => {
expect(formattedAmount).toBe('1000000000');
});
});

describe('getRoundedAmount', () => {
it('returns a rounded number with specified decimal places', () => {
const balance = '0.0002851826238227';
const fractionDigits = 5;
const result = getRoundedAmount(balance, fractionDigits);
expect(result).toBe('0.00029');
});

it('returns a rounded number with more decimal places than available', () => {
const balance = '123.456';
const fractionDigits = 10;
const result = getRoundedAmount(balance, fractionDigits);
expect(result).toBe('123.456');
});
});
5 changes: 5 additions & 0 deletions src/swap/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,8 @@ export function formatTokenAmount(amount: string, decimals: number) {
const numberAmount = Number(amount) / Math.pow(10, decimals);
return numberAmount.toString();
}

export function getRoundedAmount(balance: string, fractionDigits: number) {
const parsedBalance = parseFloat(balance);
return Number(parsedBalance)?.toFixed(fractionDigits).replace(/0+$/, '');
}
Loading