Skip to content
Open
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
241 changes: 241 additions & 0 deletions docs/pages/hooks/useBalance.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
---
layout: docs
---

import React, { useState } from "react";
import { useBalance } from "@scaffold-ui/hooks";
import { DocsProvider } from "../../components/DocsProvider";
import { mainnet } from "viem/chains";

# useBalance Hook

The `useBalance` hook fetches and watches an address balance on a given chain, pairing live USD conversion.

## Import

```tsx
import { useBalance } from "@scaffold-ui/hooks";
```

## Usage

```tsx
const {
displayUsdMode,
toggleDisplayUsdMode,
formattedBalance,
balanceInUsd,
balance,
isBalanceLoading,
isBalanceError,
isNativeCurrencyPriceLoading,
isNativeCurrencyPriceError,
isLoading,
isError,
} = useBalance({
address: "0xd8da6bf26964af9d7eed9e03e53415d37aa96045",
chain: mainnet,
defaultUsdMode: true,
});
```

## Parameters

| Parameter | Type | Default | Description |
| ---------------- | ------------------------ | ------- | --------------------------------------------------------------------------- |
| `address` | `Address` _(optional)_ | - | The address to watch. When omitted, the hook returns zeroed balance values. |
| `chain` | `Chain` | - | The **viem** chain configuration used for fetching balances and USD prices. |
| `defaultUsdMode` | `boolean` _(optional)_ | `false` | If `true` and price data is available, show USD values by default. |

## Return Values

| Property | Type | Description |
| ------------------------------ | -------------------------------- | --------------------------------------------------------------------------- |
| `displayUsdMode` | `boolean` | Whether the display is currently set to USD. |
| `toggleDisplayUsdMode` | `() => void` | Toggle between native and USD display (only active when price data exists). |
| `formattedBalance` | `number` | Native balance normalized with `formatEther`. |
| `balanceInUsd` | `number` | USD value derived from `formattedBalance * nativeCurrencyPrice`. |
| `balance` | `GetBalanceReturnType \| undefined` | Raw wagmi balance payload containing value, decimals, and symbol. |
| `isBalanceLoading` | `boolean` | Loading state for the balance fetch. |
| `isBalanceError` | `boolean` | Error state for the balance fetch. |
| `isNativeCurrencyPriceLoading` | `boolean` | Loading state for fetching the native currency price. |
| `isNativeCurrencyPriceError` | `boolean` | Error state for fetching the native currency price. |
| `isLoading` | `boolean` | Combined loading state: balance data or price is still loading. |
| `isError` | `boolean` | Combined error state: balance data or price failed to load. |

:::info
USD display is enabled only after the native currency price has been fetched. If the price is not available, toggling to USD is disabled and native balance is shown.
:::

## Live Examples

### Basic Usage

Display a live balance with an inline USD toggle.

export function UseBalanceBasicExample() {
const address = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045";
const {
formattedBalance,
balanceInUsd,
displayUsdMode,
toggleDisplayUsdMode,
isLoading,
} = useBalance({
address,
chain: mainnet,
});

return (
<div>
<p>
Balance: {displayUsdMode ? `$${balanceInUsd.toLocaleString()}` : `${formattedBalance.toLocaleString()} ETH`}
</p>
<button onClick={toggleDisplayUsdMode} disabled={isLoading}>
Toggle USD / ETH
</button>
</div>
);
}

<DocsProvider>
<UseBalanceBasicExample />
<div style={{ height: 12 }} />

</DocsProvider>

```tsx
import React from "react";
import { useBalance } from "@scaffold-ui/hooks";
import { mainnet } from "viem/chains";

function BalanceWithToggle() {
const address = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045";
const {
formattedBalance,
balanceInUsd,
displayUsdMode,
toggleDisplayUsdMode,
isLoading,
} = useBalance({
address,
chain: mainnet,
});

return (
<div>
<p>
Balance: {displayUsdMode ? `$${balanceInUsd.toLocaleString()}` : `${formattedBalance.toLocaleString()} ETH`}
</p>
<button onClick={toggleDisplayUsdMode} disabled={isLoading}>
Toggle USD / ETH
</button>
</div>
);
}
```

### Loading and Error States

Handle asynchronous fetch states while keeping the toggle experience consistent.

export function UseBalanceLoadingErrorExample() {
const [isValidAddress, setIsValidAddress] = useState(true);
const validAddress = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045";
const brokenAddress = "0x";
const {
formattedBalance,
balanceInUsd,
displayUsdMode,
toggleDisplayUsdMode,
isLoading,
isError,
} = useBalance({
address: isValidAddress ? validAddress : brokenAddress,
chain: mainnet,
defaultUsdMode: true,
});

if (isLoading) return <p>Fetching balance…</p>;
if (isError) return (
<div>
<p style={{ color: "red" }}>Could not fetch balance</p>
<button
style={{ display: "block", padding: "8px", background: "#dae8ff", borderRadius: "4px", marginTop: "4px", border: "none", cursor: "pointer", color: "#000" }}
onClick={() => setIsValidAddress((v) => !v)}
>
Fetch balance of the valid address
</button>
</div>
);

return (
<div>
<p>Balance: {displayUsdMode ? `$${balanceInUsd.toLocaleString()}` : `${formattedBalance.toLocaleString()} ETH`}</p>
<button onClick={toggleDisplayUsdMode}>Toggle USD / ETH</button>

<button
style={{ display: "block", padding: "8px", background: "#dae8ff", borderRadius: "4px", marginTop: "4px", border: "none", cursor: "pointer", color: "#000" }}
onClick={() => setIsValidAddress((v) => !v)}
>
Try to fetch balance of the broken address
</button>
</div>
);
}

<DocsProvider>
<UseBalanceLoadingErrorExample />
</DocsProvider>

```tsx
import React, { useState } from "react";
import { useBalance } from "@scaffold-ui/hooks";
import { mainnet } from "viem/chains";

function BalanceWithLoadingStates() {
const [isValidAddress, setIsValidAddress] = useState(true);
const validAddress = "0xd8da6bf26964af9d7eed9e03e53415d37aa96045";
const brokenAddress = "0x";
const {
formattedBalance,
balanceInUsd,
displayUsdMode,
toggleDisplayUsdMode,
isLoading,
isError,
} = useBalance({
address: isValidAddress ? validAddress : brokenAddress,
chain: mainnet,
defaultUsdMode: true,
});

if (isLoading) return <p>Fetching balance…</p>;
if (isError) return (
<div>
<p style={{ color: "red" }}>Could not fetch balance</p>
<button
style={{ display: "block", padding: "8px", background: "#dae8ff", borderRadius: "4px", marginTop: "4px", border: "none", cursor: "pointer", color: "#000" }}
onClick={() => setIsValidAddress((v) => !v)}
>
Fetch balance of the valid address
</button>
</div>
);

return (
<div>
<p>
Balance: {displayUsdMode ? `$${balanceInUsd.toLocaleString()}` : `${formattedBalance.toLocaleString()} ETH`}
</p>
<button onClick={toggleDisplayUsdMode}>Toggle USD / ETH</button>
<button
style={{ display: "block", padding: "8px", background: "#dae8ff", borderRadius: "4px", marginTop: "4px", border: "none", cursor: "pointer", color: "#000" }}
onClick={() => setIsValidAddress((v) => !v)}
>
Try to fetch balance of the broken address
</button>
</div>
);
}
```
152 changes: 152 additions & 0 deletions docs/pages/hooks/useEtherInput.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
---
layout: docs
---

import React, { useState } from "react";
import { useEtherInput } from "@scaffold-ui/hooks";
import { DocsProvider } from "../../components/DocsProvider";

# useEtherInput Hook

The `useEtherInput` hook converts between ETH and USD for a given input and display mode. It returns both values, the current native currency price, and loading/error flags so you can build responsive inputs.

## Import

```tsx
import { useEtherInput } from "@scaffold-ui/hooks";
```

## Usage

```tsx
const {
valueInEth,
valueInUsd,
nativeCurrencyPrice,
isNativeCurrencyPriceLoading,
isNativeCurrencyPriceError,
} = useEtherInput({ value, usdMode });
```

## Parameters

| Parameter | Type | Default | Description |
| --------- | --------- | ------- | ---------------------------------------------------------------- |
| `value` | `string` | - | The current input value. Interpreted as ETH when `usdMode` is `false`, USD when `true`. |
Copy link
Member

Choose a reason for hiding this comment

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

Currently, we allow to pass any string like "asdf". We shouldn't allow it or at least handle it properly. Created an issue #71

| `usdMode` | `boolean` | - | If `true`, `value` is USD; if `false`, `value` is ETH. |

## Return Values

| Property | Type | Description |
| ----------------------------- | --------- | -------------------------------------------------------------------- |
| `valueInEth` | `string` | The input value expressed in ETH. Empty string while conversion is unavailable. |
| `valueInUsd` | `string` | The input value expressed in USD. Empty string while conversion is unavailable. |
| `nativeCurrencyPrice` | `number` | The fetched native currency price in USD. `0` when not yet available. |
| `isNativeCurrencyPriceLoading`| `boolean` | Loading state for fetching the native currency price. |
| `isNativeCurrencyPriceError` | `boolean` | Error state for fetching the native currency price. |

:::info
This hook fetches price data using mainnet under the hood. When the price is not yet available, conversion outputs may be empty strings—keep showing the raw input in your UI.
:::

## Live Examples

### Basic Usage

export function UseEtherInputBasicExample() {
const [value, setValue] = useState("");
const [usdMode, setUsdMode] = useState(false);
const { valueInEth, valueInUsd, isNativeCurrencyPriceLoading } = useEtherInput({ value, usdMode });

return (
<div>
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
<input
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder={usdMode ? "Enter amount in USD" : "Enter amount in ETH"}
/>
<button onClick={() => setUsdMode((m) => !m)}>
{usdMode ? "USD" : "ETH"}
</button>
</div>
{isNativeCurrencyPriceLoading ? (
<p>Fetching price...</p>
) : (
<p>
ETH: <strong>{valueInEth || "–"}</strong> | USD: <strong>{valueInUsd || "–"}</strong>
</p>
)}
</div>
);
}

<DocsProvider>
<UseEtherInputBasicExample />
</DocsProvider>

```tsx
import React, { useState } from "react";
import { useEtherInput } from "@scaffold-ui/hooks";

function EtherUsdConverter() {
const [value, setValue] = useState("");
const [usdMode, setUsdMode] = useState(false);
const { valueInEth, valueInUsd, isNativeCurrencyPriceLoading } = useEtherInput({ value, usdMode });

return (
<div>
<div style={{ display: "flex", gap: 8, alignItems: "center" }}>
<input
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder={usdMode ? "Enter amount in USD" : "Enter amount in ETH"}
/>
<button onClick={() => setUsdMode((m) => !m)}>{usdMode ? "USD" : "ETH"}</button>
</div>
{isNativeCurrencyPriceLoading ? (
<p>Fetching price...</p>
) : (
<p>
ETH: <strong>{valueInEth || "–"}</strong> | USD: <strong>{valueInUsd || "–"}</strong>
</p>
)}
</div>
);
}
```

### With Error Handling

export function UseEtherInputErrorHint() {
const [value, setValue] = useState("1000");
const [usdMode] = useState(true);
const { valueInEth, valueInUsd, isNativeCurrencyPriceError } = useEtherInput({ value, usdMode });

if (isNativeCurrencyPriceError) {
Copy link
Member

Choose a reason for hiding this comment

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

Again, not sure how to make it work here. I think let's keep it as is for now

return <p style={{ color: "red" }}>Price feed unavailable. Showing entered value: ${valueInUsd}</p>;
}

return <p>ETH: {valueInEth || "–"} | USD: {valueInUsd || "–"}</p>;
}

<DocsProvider>
<UseEtherInputErrorHint />
</DocsProvider>

```tsx
import React, { useState } from "react";
import { useEtherInput } from "@scaffold-ui/hooks";

function ConverterWithErrors() {
const [value, setValue] = useState("1000");
const [usdMode] = useState(true);
const { valueInEth, valueInUsd, isNativeCurrencyPriceError } = useEtherInput({ value, usdMode });

if (isNativeCurrencyPriceError) {
return <p style={{ color: "red" }}>Price feed unavailable. Showing entered value: ${valueInUsd}</p>;
}

return <p>ETH: {valueInEth || "–"} | USD: {valueInUsd || "–"}</p>;
}
```
Loading