{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "batch-transaction",
  "title": "Batch Transaction",
  "description": "Runs several calls (e.g. approve + swap) as one action: a single wallet prompt via EIP-5792 wallet_sendCalls when the wallet reports atomic support (useCapabilities), else one transaction per call, waiting for each. Step list with per-step status, step-counting labels ('Confirm 2 of 3 in wallet…'), network switch, rejection shown as cancelled. mode: auto | atomic | sequential. Exports useBatchTransaction.",
  "dependencies": [
    "wagmi",
    "viem",
    "lucide-react"
  ],
  "registryDependencies": [
    "button",
    "@0xui/connect-wallet",
    "@0xui/morph-text",
    "@0xui/0xui-utils"
  ],
  "files": [
    {
      "path": "registry/default/components/batch-transaction.tsx",
      "content": "// Docs: https://0xui.io/components/batch-transaction.md\nimport { CheckIcon, CircleIcon, Loader2Icon, XIcon } from \"lucide-react\";\nimport { useState, type ComponentProps, type ReactNode } from \"react\";\nimport type { Address, Hex } from \"viem\";\nimport {\n  useCapabilities,\n  useChains,\n  useConfig,\n  useConnection,\n  useSendCalls,\n  useSendTransaction,\n  useSwitchChain,\n} from \"wagmi\";\nimport { getPublicClient, waitForCallsStatus } from \"wagmi/actions\";\nimport { ConnectWalletDialog } from \"@/components/connect-wallet\";\nimport { MorphText } from \"@/components/morph-text\";\nimport { Button } from \"@/components/ui/button\";\nimport { agentConfirmText, errorCode, isUserRejection } from \"@/lib/0xui-utils\";\nimport { cn } from \"@/lib/utils\";\n\nexport type BatchCall = {\n  to: Address;\n  data?: Hex;\n  value?: bigint;\n  /** Step name shown in the list, e.g. \"Approve USDC\". */\n  label?: string;\n};\n\n/**\n * \"atomic\" sends every call in one wallet prompt (EIP-5792). \"sequential\"\n * sends them one by one, waiting for each to be mined. \"auto\" picks atomic\n * when the wallet reports support for it on the chain.\n */\nexport type BatchMode = \"auto\" | \"atomic\" | \"sequential\";\n\nexport type BatchPhase =\n  | \"idle\"\n  | \"switching\"\n  | \"confirming\"\n  | \"pending\"\n  | \"success\"\n  | \"reverted\"\n  | \"cancelled\"\n  | \"error\";\n\nexport type StepState = \"todo\" | \"active\" | \"done\" | \"failed\";\n\n/** Send a list of calls atomically when the wallet supports it, else one at a time. */\nexport function useBatchTransaction({\n  calls,\n  chainId,\n  mode = \"auto\",\n}: {\n  calls: readonly BatchCall[];\n  chainId: number;\n  mode?: BatchMode;\n}) {\n  const config = useConfig();\n  const connection = useConnection();\n  const chains = useChains();\n  const switchChain = useSwitchChain();\n  const sendCalls = useSendCalls();\n  const sendTransaction = useSendTransaction();\n  const capabilities = useCapabilities({\n    chainId,\n    query: { enabled: connection.status === \"connected\" && mode === \"auto\" },\n  });\n\n  const [phase, setPhase] = useState<BatchPhase>(\"idle\");\n  const [step, setStep] = useState(0);\n  const [error, setError] = useState<Error>();\n\n  const atomicStatus = (capabilities.data as { atomic?: { status?: string } } | undefined)?.atomic\n    ?.status;\n  const atomic =\n    mode === \"atomic\" ||\n    (mode === \"auto\" && (atomicStatus === \"supported\" || atomicStatus === \"ready\"));\n  const wrongChain = connection.status === \"connected\" && connection.chainId !== chainId;\n  const targetChain = chains.find((c) => c.id === chainId);\n\n  const fail = (e: unknown) => {\n    const err = e instanceof Error ? e : new Error(String(e));\n    setError(err);\n    setPhase(isUserRejection(err) ? \"cancelled\" : \"error\");\n  };\n\n  const switchToTarget = async () => {\n    setError(undefined);\n    setPhase(\"switching\");\n    try {\n      await switchChain.mutateAsync({ chainId: chainId as (typeof chains)[number][\"id\"] });\n      setPhase(\"idle\");\n    } catch (e) {\n      fail(e);\n    }\n  };\n\n  const execute = async () => {\n    setError(undefined);\n    setStep(0);\n    try {\n      if (atomic) {\n        setPhase(\"confirming\");\n        const { id } = await sendCalls.mutateAsync({\n          chainId,\n          calls: calls.map(({ to, data, value }) => ({ to, data, value })),\n        });\n        setPhase(\"pending\");\n        const result = await waitForCallsStatus(config, { id });\n        setStep(calls.length);\n        setPhase(result.status === \"success\" ? \"success\" : \"reverted\");\n        return;\n      }\n      const client = getPublicClient(config, { chainId });\n      for (const [i, call] of calls.entries()) {\n        setStep(i);\n        setPhase(\"confirming\");\n        const hash = await sendTransaction.mutateAsync({\n          chainId,\n          to: call.to,\n          data: call.data,\n          value: call.value,\n        });\n        setPhase(\"pending\");\n        const receipt = await client!.waitForTransactionReceipt({ hash });\n        if (receipt.status === \"reverted\") {\n          setPhase(\"reverted\");\n          return;\n        }\n      }\n      setStep(calls.length);\n      setPhase(\"success\");\n    } catch (e) {\n      fail(e);\n    }\n  };\n\n  const stepState = (i: number): StepState => {\n    if (phase === \"success\" || i < step) return \"done\";\n    if (i > step) return \"todo\";\n    if (phase === \"reverted\" || phase === \"error\") return \"failed\";\n    if (phase === \"confirming\" || phase === \"pending\") return \"active\";\n    return \"todo\";\n  };\n\n  return {\n    phase,\n    step,\n    error,\n    atomic,\n    wrongChain,\n    targetChain,\n    isConnected: connection.status === \"connected\",\n    execute,\n    switchToTarget,\n    stepState,\n    reset: () => {\n      setPhase(\"idle\");\n      setStep(0);\n      setError(undefined);\n    },\n  };\n}\n\nexport type BatchTransactionProps = Omit<ComponentProps<typeof Button>, \"onClick\" | \"children\"> & {\n  calls: readonly BatchCall[];\n  chainId: number;\n  mode?: BatchMode;\n  /** Button label. */\n  children?: ReactNode;\n  /**\n   * What a browser agent must ask a person before pressing the button, set\n   * as `data-agent-confirm`. Defaults to the label plus what it does. Pass\n   * `false` to drop it.\n   */\n  agentConfirm?: string | false;\n};\n\n/**\n * Runs several calls as one action, e.g. approve then swap. Uses a single\n * wallet prompt when the wallet supports atomic batches (EIP-5792), and\n * otherwise sends them one by one. A step list shows progress either way.\n */\nexport function BatchTransaction({\n  calls,\n  chainId,\n  mode = \"auto\",\n  children = \"Confirm\",\n  agentConfirm,\n  className,\n  disabled,\n  ...buttonProps\n}: BatchTransactionProps) {\n  const [connectOpen, setConnectOpen] = useState(false);\n  const batch = useBatchTransaction({ calls, chainId, mode });\n  const busy =\n    batch.phase === \"switching\" || batch.phase === \"confirming\" || batch.phase === \"pending\";\n  const total = calls.length;\n  const current = Math.min(batch.step + 1, total);\n\n  let label: ReactNode = children;\n  let action: (() => void) | undefined = batch.execute;\n  if (!batch.isConnected) {\n    label = \"Connect wallet\";\n    action = () => setConnectOpen(true);\n  } else if (batch.phase === \"switching\") {\n    label = \"Switching network…\";\n  } else if (batch.phase === \"confirming\") {\n    label =\n      batch.atomic || total === 1\n        ? \"Confirm in wallet…\"\n        : `Confirm ${current} of ${total} in wallet…`;\n  } else if (batch.phase === \"pending\") {\n    label = batch.atomic || total === 1 ? \"Pending…\" : `Pending ${current} of ${total}…`;\n  } else if (batch.phase === \"success\") {\n    label = \"Done\";\n    action = undefined;\n  } else if (batch.wrongChain) {\n    label = `Switch to ${batch.targetChain?.name ?? \"the right network\"}`;\n    action = batch.switchToTarget;\n  }\n\n  return (\n    <div\n      data-slot=\"batch-transaction\"\n      data-phase={batch.phase}\n      data-error={errorCode(batch.phase, batch.error)}\n      data-atomic={batch.atomic || undefined}\n      className={cn(\"flex flex-col gap-3\", className)}\n    >\n      <ol aria-label=\"Steps\" className=\"flex flex-col gap-2 text-sm\">\n        {calls.map((call, i) => (\n          <li key={i} className=\"flex items-center gap-2\">\n            <StepIcon state={batch.stepState(i)} />\n            <span>{call.label ?? `Step ${i + 1}`}</span>\n          </li>\n        ))}\n      </ol>\n      <Button\n        {...buttonProps}\n        disabled={disabled || busy || !action}\n        aria-busy={busy || undefined}\n        onClick={action}\n        data-agent-confirm={\n          agentConfirm === false\n            ? undefined\n            : (agentConfirm ??\n              agentConfirmText(\n                children,\n                `sends ${calls.length} calls on ${batch.targetChain?.name ?? \"the selected network\"} from your wallet`,\n              ))\n        }\n      >\n        {busy && <Loader2Icon aria-hidden className=\"animate-spin\" />}\n        {batch.phase === \"success\" && <CheckIcon aria-hidden />}\n        <MorphText>{label}</MorphText>\n      </Button>\n      <p role=\"status\" className=\"text-xs text-muted-foreground\">\n        {batch.phase === \"cancelled\"\n          ? \"Cancelled in wallet.\"\n          : batch.phase === \"idle\" && batch.isConnected && total > 1\n            ? batch.atomic\n              ? \"One wallet prompt for all steps.\"\n              : `${total} wallet prompts, one per step.`\n            : \"\"}\n      </p>\n      {batch.phase === \"reverted\" && (\n        <p role=\"alert\" className=\"text-sm text-destructive\">\n          {batch.atomic\n            ? \"The batch reverted. None of the steps took effect.\"\n            : \"A step reverted. Later steps weren't sent.\"}\n        </p>\n      )}\n      {batch.phase === \"error\" && batch.error && (\n        <p role=\"alert\" className=\"text-sm text-destructive\">\n          {(batch.error as { shortMessage?: string }).shortMessage ?? batch.error.message}\n        </p>\n      )}\n      <ConnectWalletDialog open={connectOpen} onOpenChange={setConnectOpen} />\n    </div>\n  );\n}\n\nfunction StepIcon({ state }: { state: StepState }) {\n  const className = \"size-4 shrink-0\";\n  if (state === \"done\")\n    return <CheckIcon aria-label=\"Done\" className={cn(className, \"text-emerald-500\")} />;\n  if (state === \"failed\")\n    return <XIcon aria-label=\"Failed\" className={cn(className, \"text-destructive\")} />;\n  if (state === \"active\")\n    return (\n      <Loader2Icon\n        aria-label=\"In progress\"\n        className={cn(className, \"animate-spin text-muted-foreground\")}\n      />\n    );\n  return <CircleIcon aria-label=\"Not started\" className={cn(className, \"text-muted-foreground\")} />;\n}\n",
      "type": "registry:component"
    }
  ],
  "docs": "Docs: https://0xui.io/components/batch-transaction.md",
  "categories": [
    "transactions"
  ],
  "type": "registry:component"
}