# Convert

> A two-sided exchange block joined by a live rate hairline that shortens from both ends as the quote ages, re-quotes in place with delta and snaps taut on lock.

Currency transfers, token swaps and credit top-ups usually hide quote expiry behind a separate countdown badge or flash a stale-price toast after you press Confirm. Convert makes the hairline between You pay and You receive the quote clock itself: two symmetrical hairline wings shorten from both edges toward the centre rate pill as expiresAt approaches. When a quote expires it re-quotes in place through your getQuote callback without blanking the card, rolling the received figure smoothly and marking the percentage move (+0.34% / -0.24%) beside the rate. Entering Review locks the quote so both hairline wings spring taut to full width with a Locked badge and transparent fee breakdown, before onConvert settles with an emerald Bayer floor pulse.

## Install

```bash
npx shadcn@latest add https://hairlineui.com/r/convert.json
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: `lucide-react`
- Hairline UI components it needs (the CLI installs them too): `text-morph`, `number-roll`
- Docs and live preview: https://hairlineui.com/ui/convert
- Registry item (source): https://hairlineui.com/r/convert.json

## Usage

```tsx
import { Convert } from "@/components/convert";

<Convert
  assets={[
    { code: "USD", name: "US Dollar", symbol: "$", balance: 4850 },
    { code: "EUR", name: "Euro", symbol: "€", balance: 1240.5 },
  ]}
  getQuote={(from, to, amount) => fetchQuote(from, to, amount)}
  onConvert={(quote) => executeConversion(quote)}
/>
```

## Wired to a server FX pricing and execution route

Keep all pricing and ledger mutations on your backend; Convert handles the ticking quote, lock step and inline error recovery.

```tsx
"use client";
import { Convert, type ConvertAsset, type ConvertQuote } from "@/components/convert";

export function FxConvertCard({ assets }: { assets: ConvertAsset[] }) {
  return (
    <Convert
      assets={assets}
      presets={[100, 500, 1000]}
      getQuote={async (from, to, amount) => {
        const res = await fetch(`/api/fx/quote?from=${from}&to=${to}&amount=${amount}`);
        if (!res.ok) throw new Error("Could not fetch quote");
        return (await res.json()) as ConvertQuote;
      }}
      onConvert={async (quote) => {
        const res = await fetch("/api/fx/convert", {
          method: "POST",
          body: JSON.stringify({ quoteId: quote.id }),
        });
        if (!res.ok) throw new Error((await res.json()).message ?? "Conversion failed");
      }}
    />
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `assets` | `ConvertAsset[]` | – | List of assets ({ code, name, symbol?, decimals?, balance?, badge? }) available in both pickers. |
| `getQuote` | `(from, to, amount) => Promise<ConvertQuote> \| ConvertQuote` | – | Returns { from, to, fromAmount, toAmount, rate, fee?, feeLabel?, expiresAt, deltaPct? }. |
| `onConvert` | `(quote: ConvertQuote) => Promise<unknown> \| unknown` | – | Executes the locked conversion; throw an Error to show its message inline. |
| `defaultFrom / defaultTo / defaultAmount` | `string / string / number \| null` | `assets[0] / assets[1] / 250` | Initial pair and pay amount. |
| `presets / locale / title / sound` | `number[] / string / string / boolean` | `— / "en-US" / "Convert" / false` | Quick amount buttons, Intl locale, header title and opt-in Web Audio cues. |

## States

- **live quote**: Both hairline wings shorten symmetrically inward toward the rate pill at 60fps via GPU scaleX while the countdown ticks.
- **re-quoted**: When expiresAt arrives, getQuote() refreshes in place, the received figure rolls smoothly and a coloured +/-% delta chip appears beside the rate.
- **review locked**: Both hairline wings snap taut to 100% width on a spring, inputs lock and the fee and guaranteed payout rows open inline.
- **overdraft**: Amounts above balance tint crimson, report the exact shortfall and disable Review until adjusted.
- **settled**: After onConvert resolves, an emerald 8×8 Bayer pulse sweeps the lower edge and a compact settlement receipt replaces the review rows.
- **error**: If onConvert rejects, the card recoils gently, shows your error message inline and keeps the locked quote ready to retry.

## What it handles

A trustworthy conversion surface has to keep pricing transparent while a quote ticks down and never let a stale rate execute silently.

- **The rate hairline is the quote clock**: Two symmetrical GPU-composited hairline wings shorten inward toward the centre rate pill as expiresAt counts down, turning amber in the final 3 seconds.
- **In-place re-quote with rate delta**: On expiry the card calls getQuote() in place, refills the wings, rolls the received figure smoothly and shows the percentage change beside the rate.
- **Review locks the quote taut**: Clicking Review snaps both hairline wings taut on a spring, locks inputs and opens the exact locked-rate, fee and guaranteed-payout breakdown.
- **Balance cap and overdraft guard**: Pass balance on any asset to unlock one-click Max fill, inline crimson shortfall copy and automatic CTA disable when over balance.
- **App-owned pricing and settlement**: Your backend stays in charge via getQuote(from, to, amount) and onConvert(quote); thrown errors surface cleanly inside the card without clearing the amount.
- **Accessible keyboard asset switching**: Both asset pickers support ArrowUp/ArrowDown, Enter, Escape and live swap direction with a spring-rotated swap icon.

## Replaces

currency swap card, quote expiry timer badge, locked rate review modal, FX fee summary drawer

## Where it fits

- **Multi-currency FX wallets**: Let customers exchange USD, EUR, GBP and JPY against live mid-market quotes with transparent spread and locked review.
- **Crypto and stablecoin swaps**: Quote token swaps from your own routing API, re-quote automatically on expiry and surface exact price drift before signing.
- **Usage credits and points top-ups**: Convert account balance or card spend into compute credits or reward points with zero-fee clarity and quick presets.
- **Treasury and payout dashboards**: Give finance operators an overdraft-checked converter that pairs cleanly with Wallet and Amount field.

## Notes

- The shrinking rate wings write scaleX directly to two DOM refs inside requestAnimationFrame and pause automatically when scrolled off screen.
- The outer card avoids overflow-hidden so both asset dropdown menus open cleanly without bottom clipping.
- Under prefers-reduced-motion: reduce, the hairline wings hold steady without per-frame animation, the swap icon turns cleanly without spin and received values update directly.

License: MIT (https://hairlineui.com/license#components)
