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

[SDK] USD balance for AccountBalance #5533

Merged
merged 1 commit into from
Dec 7, 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
67 changes: 67 additions & 0 deletions .changeset/fair-plants-pretend.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
---
"thirdweb": minor
---
The Connected-details button now shows USD value next to the token balance.

### Breaking change to the AccountBalance
The formatFn props now takes in an object of type `AccountBalanceInfo`. The old `formatFn` was inflexible because it only allowed you to format the balance value.
With this new version, you have access to both the balance and symbol.
```tsx
import { AccountBalance, type AccountBalanceInfo } from "thirdweb/react";

<AccountBalance
// Show the symbol in lowercase, before the balance
formatFn={(props: AccountBalanceInfo) => `${props.symbol.toLowerCase()} ${props.balance}`}
/>
```

AccountBalance now supports showing the token balance in fiat value (only USD supported at the moment)
```tsx
<AccountBalance
showBalanceInFiat="USD"
/>
```

The `formatFn` prop now takes in an object of type `AccountBalanceInfo` and outputs a string
```tsx
import { AccountBalance, type AccountBalanceInfo } from "thirdweb/react";

<AccountBalance
formatFn={(props: AccountBalanceInfo) => `${props.balance}---${props.symbol.toLowerCase()}`}
/>

// Result: 11.12---eth
```

### ConnectButton also supports displaying balance in fiat since it uses AccountBalance internally
```tsx
<ConnectButton
// Show USD value on the button
detailsButton={{
showBalanceInFiat: "USD",
}}

// Show USD value on the modal
detailsModal={{
showBalanceInFiat: "USD",
}}
/>
```

### Export utils functions:
formatNumber: Round up a number to a certain decimal place
```tsx
import { formatNumber } from "thirdweb/utils";
const value = formatNumber(12.1214141, 1); // 12.1
```

shortenLargeNumber: Shorten the string for large value. Mainly used for the AccountBalance's `formatFn`
```tsx
import { shortenLargeNumber } from "thirdweb/utils";
const numStr = shortenLargeNumber(1_000_000_000)
```

### Fix to ConnectButton
The social image of the Details button now display correctly for non-square image.

### Massive test coverage improvement for the Connected-button components
1 change: 1 addition & 0 deletions packages/thirdweb/src/exports/react.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ export {
export {
AccountBalance,
type AccountBalanceProps,
type AccountBalanceInfo,
} from "../react/web/ui/prebuilt/Account/balance.js";
export {
AccountName,
Expand Down
3 changes: 3 additions & 0 deletions packages/thirdweb/src/exports/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,6 @@ export type {
AbiConstructor,
AbiFallback,
} from "abitype";

export { shortenLargeNumber } from "../utils/shortenLargeNumber.js";
export { formatNumber } from "../utils/formatNumber.js";
22 changes: 21 additions & 1 deletion packages/thirdweb/src/pay/convert/cryptoToFiat.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { TEST_CLIENT } from "~test/test-clients.js";
import { TEST_ACCOUNT_A } from "~test/test-wallets.js";
import { base } from "../../chains/chain-definitions/base.js";
Expand Down Expand Up @@ -92,4 +92,24 @@ describe.runIf(process.env.TW_SECRET_KEY)("Pay: crypto-to-fiat", () => {
`Error: ${TEST_ACCOUNT_A.address} on chainId: ${base.id} is not a valid contract address.`,
);
});
it("should throw if response is not OK", async () => {
global.fetch = vi.fn();
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 400,
statusText: "Bad Request",
});
await expect(() =>
convertCryptoToFiat({
chain: base,
fromTokenAddress: NATIVE_TOKEN_ADDRESS,
fromAmount: 1,
to: "USD",
client: TEST_CLIENT,
}),
).rejects.toThrowError(
`Failed to fetch USD value for token (${NATIVE_TOKEN_ADDRESS}) on chainId: ${base.id}`,
);
vi.restoreAllMocks();
});
});
3 changes: 2 additions & 1 deletion packages/thirdweb/src/pay/convert/cryptoToFiat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { getContract } from "../../contract/contract.js";
import { isAddress } from "../../utils/address.js";
import { getClientFetch } from "../../utils/fetch.js";
import { getPayConvertCryptoToFiatEndpoint } from "../utils/definitions.js";
import type { SupportedFiatCurrency } from "./type.js";

/**
* Props for the `convertCryptoToFiat` function
Expand All @@ -31,7 +32,7 @@ export type ConvertCryptoToFiatParams = {
* The fiat symbol. e.g "USD"
* Only USD is supported at the moment.
*/
to: "USD";
to: SupportedFiatCurrency;
};

/**
Expand Down
22 changes: 21 additions & 1 deletion packages/thirdweb/src/pay/convert/fiatToCrypto.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { TEST_CLIENT } from "~test/test-clients.js";
import { TEST_ACCOUNT_A } from "~test/test-wallets.js";
import { base } from "../../chains/chain-definitions/base.js";
Expand Down Expand Up @@ -93,4 +93,24 @@ describe.runIf(process.env.TW_SECRET_KEY)("Pay: fiatToCrypto", () => {
`Error: ${TEST_ACCOUNT_A.address} on chainId: ${base.id} is not a valid contract address.`,
);
});
it("should throw if response is not OK", async () => {
global.fetch = vi.fn();
global.fetch = vi.fn().mockResolvedValue({
ok: false,
status: 400,
statusText: "Bad Request",
});
await expect(() =>
convertFiatToCrypto({
chain: ethereum,
to: NATIVE_TOKEN_ADDRESS,
fromAmount: 1,
from: "USD",
client: TEST_CLIENT,
}),
).rejects.toThrowError(
`Failed to convert USD value to token (${NATIVE_TOKEN_ADDRESS}) on chainId: 1`,
);
vi.restoreAllMocks();
});
});
5 changes: 3 additions & 2 deletions packages/thirdweb/src/pay/convert/fiatToCrypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { getContract } from "../../contract/contract.js";
import { isAddress } from "../../utils/address.js";
import { getClientFetch } from "../../utils/fetch.js";
import { getPayConvertFiatToCryptoEndpoint } from "../utils/definitions.js";
import type { SupportedFiatCurrency } from "./type.js";

/**
* Props for the `convertFiatToCrypto` function
Expand All @@ -18,7 +19,7 @@ export type ConvertFiatToCryptoParams = {
* The fiat symbol. e.g: "USD"
* Currently only USD is supported.
*/
from: "USD";
from: SupportedFiatCurrency;
/**
* The total amount of fiat to convert
* e.g: If you want to convert 2 cents to USD, enter `0.02`
Expand Down Expand Up @@ -101,7 +102,7 @@ export async function convertFiatToCrypto(
const response = await getClientFetch(client)(url);
if (!response.ok) {
throw new Error(
`Failed to convert ${to} value to token (${to}) on chainId: ${chain.id}`,
`Failed to convert ${from} value to token (${to}) on chainId: ${chain.id}`,
);
}

Expand Down
5 changes: 5 additions & 0 deletions packages/thirdweb/src/pay/convert/type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const SUPPORTED_FIAT_CURRENCIES = ["USD"] as const;
/**
* @internal
*/
export type SupportedFiatCurrency = (typeof SUPPORTED_FIAT_CURRENCIES)[number];
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { Chain } from "../../../../chains/types.js";
import type { ThirdwebClient } from "../../../../client/client.js";
import type { BuyWithCryptoStatus } from "../../../../pay/buyWithCrypto/getStatus.js";
import type { BuyWithFiatStatus } from "../../../../pay/buyWithFiat/getStatus.js";
import type { SupportedFiatCurrency } from "../../../../pay/convert/type.js";
import type { FiatProvider } from "../../../../pay/utils/commonTypes.js";
import type { AssetTabs } from "../../../../react/web/ui/ConnectWallet/screens/ViewAssets.js";
import type { PreparedTransaction } from "../../../../transaction/prepare-transaction.js";
Expand Down Expand Up @@ -320,6 +321,12 @@ export type ConnectButton_detailsModalOptions = {
* Note: If an empty array is passed, the [View Funds] button will be hidden
*/
assetTabs?: AssetTabs[];

/**
* Show the token balance's value in fiat.
* Note: Not all tokens are resolvable to a fiat value. In that case, nothing will be shown.
*/
showBalanceInFiat?: SupportedFiatCurrency;
};

/**
Expand Down Expand Up @@ -377,6 +384,12 @@ export type ConnectButton_detailsButtonOptions = {
* Use custom avatar URL for the connected wallet image in the `ConnectButton` details button, overriding ENS avatar or Blobbie icon.
*/
connectedAccountAvatarUrl?: string;

/**
* Show the token balance's value in fiat.
* Note: Not all tokens are resolvable to a fiat value. In that case, nothing will be shown.
*/
showBalanceInFiat?: SupportedFiatCurrency;
};

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,19 @@ describe("ConnectButton", () => {
);
expect(screen.getByText("Sign In")).toBeInTheDocument();
});

it("should render with fiat balance props", () => {
render(
<ConnectButton
client={TEST_CLIENT}
detailsButton={{
showBalanceInFiat: "USD",
}}
detailsModal={{
showBalanceInFiat: "USD",
}}
/>,
);
expect(screen.getByText("Connect Wallet")).toBeInTheDocument();
});
});
Loading
Loading