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 /> #155

Closed
wants to merge 1 commit into from
Closed
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
62 changes: 62 additions & 0 deletions src/components/Balance.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/**
* @jest-environment jsdom
*/
import React from 'react';
import { publicClient } from '../network/client';
import { render, screen } from '@testing-library/react';
import { Balance } from './Balance';
import { useOnchainActionWithCache } from '../hooks/useOnchainActionWithCache';

import '@testing-library/jest-dom';

jest.mock('../network/client');
jest.mock('../hooks/useOnchainActionWithCache');

describe('Balance', () => {
const testAddress = '0x1234567890abcdef1234567890abcdef12345678';

const mockGetBalance = publicClient.getBalance as jest.Mock;
const mockUseOnchainActionWithCache = useOnchainActionWithCache as jest.Mock;

beforeEach(() => {
jest.clearAllMocks();
});

it('displays ETH balance', async () => {
const testBalance = 49094208464446850n;
mockGetBalance.mockReturnValue(testBalance);
mockUseOnchainActionWithCache.mockImplementation(() => {
return {
data: testBalance,
isLoading: false,
};
});

render(
<span data-testid="test-id-balance">
<Balance address={testAddress} />
</span>,
);

expect(await screen.findByTestId('test-id-balance')).toHaveTextContent('0.049 ETH');
});

it('displays ETH balance with rounding', async () => {
const testBalance = 49994208464446850n;
mockGetBalance.mockReturnValue(testBalance);
mockUseOnchainActionWithCache.mockImplementation(() => {
return {
data: testBalance,
isLoading: false,
};
});

render(
<span data-testid="test-id-balance">
<Balance address={testAddress} />
</span>,
);

expect(await screen.findByTestId('test-id-balance')).toHaveTextContent('0.050 ETH');
});
});
53 changes: 53 additions & 0 deletions src/components/Balance.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import React from 'react';
import { formatEther, parseEther } from 'viem';
import type { Address } from 'viem';
import { publicClient } from '../network/client';
import { useOnchainActionWithCache } from '../hooks/useOnchainActionWithCache';

type BalanceProps = {
address: Address;
className?: string;
decimalDigits?: number;
props?: React.HTMLAttributes<HTMLSpanElement>;
};

const balanceAction = (address: Address) => async (): Promise<string> => {
try {
return await publicClient
.getBalance({
address,
})
.toString();
} catch (err) {
return '0';
}
};

/**
* Balance is a React component that renders the account balance for the given Ethereum address.
* It displays the user's balance, with the no. of decimals specified by the 'decimalDigits' prop.
* By default, 'decimalDigits' is set to 3.
*
* @param {Address} props.address - The Ethereum address for which to display the balance.
* @param {string} [className] - Optional CSS class for custom styling.
* @param {number} [decimalDigits=3] - Determines the no. of decimal digits to be displayed.
* @param {React.HTMLAttributes<HTMLSpanElement>} [props] - Additional HTML attributes for the span element.
*/
export function Balance({ address, className, decimalDigits = 3, ...props }: BalanceProps) {
Copy link
Contributor

@Sneh1999 Sneh1999 Feb 20, 2024

Choose a reason for hiding this comment

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

Can we add this functionality to the avatar if possible?

Copy link
Contributor Author

@eragon512 eragon512 Feb 20, 2024

Choose a reason for hiding this comment

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

not sure if that's the best approach here - generally, it's best to keep each component small and atomic, with a single, clear responsibility

adding balance data to the avatar might add multiple responsibilities inside a single component

if users need balance data in their avatar, having a separate component allows them to stitch the avatar and balance components together in the way they feel fits their use case best

LMK your thoughts on this

Copy link
Contributor

Choose a reason for hiding this comment

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

This week is hard for us to ship a new component.

Let's table this till the end of ETH Denver.

But, I love we at least started the convo.

const balanceKey = `balance-${address}`;
const { data: balance, isLoading } = useOnchainActionWithCache(
balanceAction(address),
balanceKey,
);

if (isLoading) {
return null;
}

return (
<span className={className} {...props}>
{parseFloat(formatEther(BigInt(balance ?? '0'))).toFixed(decimalDigits)}
{' ETH'}
</span>
);
}
Loading