{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "swap",
  "title": "Swap",
  "description": "Swap block with bring-your-own quotes: two TokenInput panels with a flip button, debounced auto-refreshing quotes from a getQuote(sellToken, buyToken, sellAmount, taker) prop (any aggregator or router), rate row (click to invert), price-impact warning, an ApproveButton step when the sell token needs an allowance, and a swap button naming the blocker (Select a token / Enter an amount / Insufficient balance / Fetching quote / No route found). Exports useSwapQuote, formatRate and the GetQuote/SwapQuote types.",
  "dependencies": [
    "viem",
    "wagmi",
    "@tanstack/react-query",
    "lucide-react"
  ],
  "registryDependencies": [
    "@0xui/token-input",
    "@0xui/token-select",
    "@0xui/approve-button",
    "@0xui/transaction-button",
    "@0xui/morph-text"
  ],
  "files": [
    {
      "path": "registry/default/components/swap.tsx",
      "content": "// Docs: https://0xui.io/blocks/swap.md\nimport { useQuery } from \"@tanstack/react-query\";\nimport { ArrowDownUpIcon } from \"lucide-react\";\nimport { useEffect, useState, type ReactNode } from \"react\";\nimport {\n  formatUnits,\n  type Address,\n  type Hash,\n  type Hex,\n  type TransactionReceipt,\n} from \"viem\";\nimport { useConnection } from \"wagmi\";\nimport { ApproveButton } from \"@/components/approve-button\";\nimport { MorphText } from \"@/components/morph-text\";\nimport { TokenInput, type TokenInputState } from \"@/components/token-input\";\nimport { isNativeToken, type Token, type TokenPrices } from \"@/components/token-select\";\nimport { TransactionButton } from \"@/components/transaction-button\";\nimport { cn } from \"@/lib/utils\";\n\nexport type SwapQuote = {\n  /** Output amount, in the buy token's smallest unit. */\n  buyAmount: bigint;\n  /** Transaction that performs the swap. */\n  transaction: { to: Address; data?: Hex; value?: bigint };\n  /** Contract that must be approved to spend the sell token, if it's an ERC-20. */\n  spender?: Address;\n  /** Price impact in percent, e.g. 0.3. Shown, and warned about above 5%. */\n  priceImpact?: number;\n};\n\nexport type GetQuote = (request: {\n  sellToken: Token;\n  buyToken: Token;\n  sellAmount: bigint;\n  /** Connected account, for quotes that need a taker. */\n  taker: Address | undefined;\n}) => Promise<SwapQuote>;\n\nfunction useDebounced<T>(value: T, delay: number) {\n  const [debounced, setDebounced] = useState(value);\n  useEffect(() => {\n    const timer = setTimeout(() => setDebounced(value), delay);\n    return () => clearTimeout(timer);\n  }, [value, delay]);\n  return debounced;\n}\n\n/** \"1 ETH = 3,150.42 USDC\" from a quote. */\nexport function formatRate(\n  sell: { token: Token; amount: bigint },\n  buy: { token: Token; amount: bigint },\n  { invert = false, locale }: { invert?: boolean; locale?: string } = {}\n) {\n  const sellUnits = Number(formatUnits(sell.amount, sell.token.decimals));\n  const buyUnits = Number(formatUnits(buy.amount, buy.token.decimals));\n  if (!sellUnits || !buyUnits) return undefined;\n  const [from, to, rate] = invert\n    ? [buy.token, sell.token, sellUnits / buyUnits]\n    : [sell.token, buy.token, buyUnits / sellUnits];\n  const formatted = new Intl.NumberFormat(locale, { maximumSignificantDigits: 6 }).format(rate);\n  return `1 ${from.symbol} = ${formatted} ${to.symbol}`;\n}\n\n/**\n * Debounced, auto-refreshing quote for the current swap. `isStale` is true\n * while the shown quote doesn't match what the user typed.\n */\nexport function useSwapQuote({\n  getQuote,\n  sellToken,\n  buyToken,\n  sellAmount,\n  refreshInterval = 15_000,\n}: {\n  getQuote: GetQuote;\n  sellToken: Token | undefined;\n  buyToken: Token | undefined;\n  sellAmount: bigint | undefined;\n  refreshInterval?: number | false;\n}) {\n  const { address } = useConnection();\n  const debounced = useDebounced(sellAmount, 400);\n  const query = useQuery({\n    queryKey: [\n      \"0xui\",\n      \"swap-quote\",\n      sellToken?.chainId,\n      sellToken?.address,\n      buyToken?.address,\n      debounced?.toString(),\n      address,\n    ],\n    queryFn: () =>\n      getQuote({ sellToken: sellToken!, buyToken: buyToken!, sellAmount: debounced!, taker: address }),\n    enabled: Boolean(sellToken && buyToken && debounced && debounced > 0n),\n    refetchInterval: refreshInterval,\n    retry: false,\n  });\n  return {\n    quote: query.data,\n    isLoading: query.isFetching && !query.data,\n    isStale: debounced !== sellAmount,\n    error: query.error,\n  };\n}\n\nexport type SwapProps = {\n  /** Tokens for both pickers. */\n  tokens: readonly Token[];\n  /** Fetch a quote. Call your aggregator or router here. */\n  getQuote: GetQuote;\n  defaultSellToken?: Token;\n  defaultBuyToken?: Token;\n  popular?: readonly string[];\n  /** Prices keyed by `chainId:address`, address or symbol, for fiat lines. */\n  prices?: TokenPrices;\n  onSubmitted?: (hash: Hash) => void;\n  onSuccess?: (receipt: TransactionReceipt) => void;\n  title?: ReactNode;\n  className?: string;\n};\n\n/**\n * Swap form: two token panels with a flip button, a live quote with rate\n * and price impact, an approval step when the sell token needs one, and a\n * swap button that names whatever is missing. Bring your own quotes via\n * `getQuote`.\n */\nexport function Swap({\n  tokens,\n  getQuote,\n  defaultSellToken,\n  defaultBuyToken,\n  popular,\n  prices,\n  onSubmitted,\n  onSuccess,\n  title = \"Swap\",\n  className,\n}: SwapProps) {\n  const [sellToken, setSellToken] = useState<Token | undefined>(defaultSellToken ?? tokens[0]);\n  const [buyToken, setBuyToken] = useState<Token | undefined>(defaultBuyToken);\n  const [sellText, setSellText] = useState(\"\");\n  const [sell, setSell] = useState<TokenInputState>();\n  const [invertRate, setInvertRate] = useState(false);\n\n  const sellAmount = sell?.amount;\n  const { quote, isLoading, isStale, error } = useSwapQuote({\n    getQuote,\n    sellToken,\n    buyToken,\n    sellAmount,\n  });\n\n  const flip = () => {\n    setSellToken(buyToken);\n    setBuyToken(sellToken);\n    setSellText(\"\");\n    setSell(undefined);\n  };\n\n  const pick = (side: \"sell\" | \"buy\") => (token: Token) => {\n    const other = side === \"sell\" ? buyToken : sellToken;\n    // Picking the other side's token swaps them.\n    if (other && other.address === token.address && other.chainId === token.chainId) return flip();\n    if (side === \"sell\") {\n      setSellToken(token);\n      setSellText(\"\");\n      setSell(undefined);\n    } else {\n      setBuyToken(token);\n    }\n  };\n\n  const blocker = !sellToken || !buyToken\n    ? \"Select a token\"\n    : !sellAmount\n      ? \"Enter an amount\"\n      : sell?.insufficient\n        ? `Insufficient ${sellToken.symbol} balance`\n        : error\n          ? \"No route found\"\n          : isLoading || isStale || !quote\n            ? \"Fetching quote…\"\n            : undefined;\n\n  const buyText =\n    quote && buyToken && !isStale ? formatUnits(quote.buyAmount, buyToken.decimals) : \"\";\n  const rate =\n    quote && sellToken && buyToken && sellAmount && !isStale\n      ? formatRate(\n          { token: sellToken, amount: sellAmount },\n          { token: buyToken, amount: quote.buyAmount },\n          { invert: invertRate }\n        )\n      : undefined;\n  const impact = quote?.priceImpact;\n\n  const swapButton = (\n    <TransactionButton\n      chainId={sellToken?.chainId}\n      transaction={!blocker ? quote?.transaction : undefined}\n      disabledReason={blocker}\n      onSubmitted={onSubmitted}\n      onSuccess={(receipt) => {\n        setSellText(\"\");\n        setSell(undefined);\n        onSuccess?.(receipt);\n      }}\n      className=\"w-full [&>button]:h-11 [&>button]:w-full\"\n    >\n      Swap\n    </TransactionButton>\n  );\n\n  const needsApproval =\n    !blocker && sellToken && !isNativeToken(sellToken) && quote?.spender && sellAmount;\n\n  return (\n    <div data-slot=\"swap\" className={cn(\"flex w-full max-w-md flex-col gap-3\", className)}>\n      {title && <h3 className=\"text-lg font-semibold\">{title}</h3>}\n      <div className=\"relative flex flex-col gap-1\">\n        <TokenInput\n          label=\"You pay\"\n          value={sellText}\n          onValueChange={(next, state) => {\n            setSellText(next);\n            setSell(state);\n          }}\n          token={sellToken}\n          onTokenChange={pick(\"sell\")}\n          tokens={tokens}\n          popular={popular}\n          prices={prices}\n        />\n        <button\n          type=\"button\"\n          aria-label=\"Switch tokens\"\n          onClick={flip}\n          className=\"absolute top-1/2 left-1/2 z-10 -translate-x-1/2 -translate-y-1/2 rounded-xl border-4 border-background bg-muted p-2 hover:bg-accent\"\n        >\n          <ArrowDownUpIcon aria-hidden className=\"size-4\" />\n        </button>\n        <TokenInput\n          label=\"You receive\"\n          value={buyText}\n          onValueChange={() => {}}\n          token={buyToken}\n          onTokenChange={pick(\"buy\")}\n          tokens={tokens}\n          popular={popular}\n          prices={prices}\n          readOnly\n          checkBalance={false}\n        />\n      </div>\n\n      <div className=\"flex min-h-5 items-center justify-between gap-2 text-sm text-muted-foreground\" aria-live=\"polite\">\n        {error ? (\n          <span role=\"alert\" className=\"text-destructive\">\n            {(error as { shortMessage?: string }).shortMessage ?? error.message}\n          </span>\n        ) : rate ? (\n          <button type=\"button\" onClick={() => setInvertRate((v) => !v)} className=\"hover:text-foreground\">\n            <MorphText>{rate}</MorphText>\n          </button>\n        ) : sellAmount && (isLoading || isStale) ? (\n          <span>Fetching quote…</span>\n        ) : (\n          <span />\n        )}\n        {impact !== undefined && rate && (\n          <span className={cn(impact > 15 ? \"text-destructive\" : impact > 5 && \"text-amber-600 dark:text-amber-400\")}>\n            <MorphText>{`Price impact ${impact.toFixed(2)}%`}</MorphText>\n          </span>\n        )}\n      </div>\n\n      {needsApproval ? (\n        <ApproveButton\n          token={sellToken}\n          spender={quote!.spender!}\n          amount={sellAmount}\n          chainId={sellToken.chainId}\n          className=\"w-full [&>button]:h-11 [&>button]:w-full\"\n        >\n          {swapButton}\n        </ApproveButton>\n      ) : (\n        swapButton\n      )}\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "docs": "Docs: https://0xui.io/blocks/swap.md",
  "categories": [
    "blocks"
  ],
  "type": "registry:block"
}