{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "transaction-button",
  "title": "Transaction Button",
  "description": "Button that sends a transaction (sendTransaction) or contract call (writeContract) and shows every step on itself: opens the wallet picker when disconnected, 'Switch to <chain>' on the wrong network, then 'Confirm in wallet…', 'Pending…', 'Done', with a status line and alerts. A wallet rejection shows as cancelled and doesn't call onError. Reverted transactions are detected. disabledReason names the blocker ('Enter an amount'). Exports useTransactionFlow and TxPhase: idle | switching | confirming | pending | success | reverted | cancelled | error. With simulate it dry-runs the call (useSimulateContract, useCall) and shows the revert reason on a disabled button before the wallet opens. Exports useTransactionSimulation and revertReason.",
  "dependencies": [
    "wagmi",
    "viem",
    "lucide-react"
  ],
  "registryDependencies": [
    "button",
    "@0xui/connect-wallet",
    "@0xui/transaction-status",
    "@0xui/morph-text",
    "@0xui/0xui-utils"
  ],
  "files": [
    {
      "path": "registry/default/components/transaction-button.tsx",
      "content": "// Docs: https://0xui.io/components/transaction-button.md\nimport { CheckIcon, Loader2Icon } from \"lucide-react\";\nimport {\n  useCallback,\n  useEffect,\n  useRef,\n  useState,\n  type ComponentProps,\n  type ReactNode,\n} from \"react\";\nimport { BaseError, ContractFunctionRevertedError, type Hash, type TransactionReceipt } from \"viem\";\nimport {\n  useCall,\n  useChains,\n  useConnection,\n  useSendTransaction,\n  useSimulateContract,\n  useSwitchChain,\n  useTransactionConfirmations,\n  useWriteContract,\n} from \"wagmi\";\nimport { ConnectWalletDialog } from \"@/components/connect-wallet\";\nimport { MorphText } from \"@/components/morph-text\";\nimport { useMinedReceipt } from \"@/components/transaction-status\";\nimport { Button } from \"@/components/ui/button\";\nimport { agentConfirmText, errorCode, isUserRejection } from \"@/lib/0xui-utils\";\nimport { cn } from \"@/lib/utils\";\n\nexport type TxPhase =\n  | \"idle\"\n  | \"switching\"\n  | \"confirming\"\n  | \"pending\"\n  | \"success\"\n  | \"reverted\"\n  | \"cancelled\"\n  | \"error\";\n\n/** Arguments for `writeContract`: `{ address, abi, functionName, args, value? }`. */\nexport type ContractRequest = Parameters<ReturnType<typeof useWriteContract>[\"mutateAsync\"]>[0];\n\n/** Arguments for `sendTransaction`: `{ to, value?, data? }`. */\nexport type TransactionRequest = Parameters<\n  ReturnType<typeof useSendTransaction>[\"mutateAsync\"]\n>[0];\n\nexport type TransactionFlowOptions = {\n  /** Chain the transaction must run on. Defaults to the current chain. */\n  chainId?: number;\n  /** Confirmations to wait for before success. */\n  confirmations?: number;\n  /** Called once the wallet returns a transaction hash. */\n  onSubmitted?: (hash: Hash) => void;\n  /** Called when the transaction is mined successfully. */\n  onSuccess?: (receipt: TransactionReceipt) => void;\n  /** Called on failure, including a reverted transaction. Not called when the user cancels. */\n  onError?: (error: Error) => void;\n};\n\n/**\n * Transaction lifecycle as one phase: switching network, waiting for the\n * wallet, pending on-chain, then success, reverted, cancelled or error.\n */\nexport function useTransactionFlow({\n  chainId,\n  confirmations = 1,\n  onSubmitted,\n  onSuccess,\n  onError,\n}: TransactionFlowOptions = {}) {\n  const connection = useConnection();\n  const chains = useChains();\n  const switchChain = useSwitchChain();\n  const write = useWriteContract();\n  const send = useSendTransaction();\n\n  const [step, setStep] = useState<TxPhase>(\"idle\");\n  const [hash, setHash] = useState<Hash>();\n  const [error, setError] = useState<Error>();\n\n  const targetChainId = chainId ?? connection.chainId;\n  const targetChain = chains.find((c) => c.id === targetChainId);\n  const wrongChain =\n    connection.status === \"connected\" &&\n    targetChainId !== undefined &&\n    connection.chainId !== targetChainId;\n\n  const receipt = useMinedReceipt({ hash, chainId: targetChainId });\n  const confirmed = useTransactionConfirmations({\n    hash,\n    chainId: targetChainId,\n    query: {\n      enabled: receipt.data?.status === \"success\" && confirmations > 1,\n      refetchInterval: 4_000,\n    },\n  });\n  const enoughConfirmations = confirmations <= 1 || Number(confirmed.data ?? 0n) >= confirmations;\n\n  const phase: TxPhase =\n    hash && step === \"pending\"\n      ? receipt.data\n        ? receipt.data.status === \"reverted\"\n          ? \"reverted\"\n          : enoughConfirmations\n            ? \"success\"\n            : \"pending\"\n        : receipt.isError\n          ? \"error\"\n          : \"pending\"\n      : step;\n\n  // Fire callbacks once per transaction, when it settles.\n  const reported = useRef<Hash>(undefined);\n  useEffect(() => {\n    const data = receipt.data;\n    if (!data || reported.current === data.transactionHash) return;\n    if (phase !== \"success\" && phase !== \"reverted\") return;\n    reported.current = data.transactionHash;\n    if (phase === \"success\") onSuccess?.(data);\n    else onError?.(new Error(\"Transaction reverted\"));\n    // Callbacks are deliberately not dependencies: only settling should fire them.\n  }, [phase, receipt.data]);\n\n  const fail = (e: unknown) => {\n    const err = e instanceof Error ? e : new Error(String(e));\n    setError(err);\n    if (isUserRejection(err)) {\n      setStep(\"cancelled\");\n    } else {\n      setStep(\"error\");\n      onError?.(err);\n    }\n  };\n\n  const switchToTarget = async () => {\n    if (targetChainId === undefined) return;\n    setError(undefined);\n    setStep(\"switching\");\n    try {\n      // Narrow to the chain-id union when the app registers its config type.\n      await switchChain.mutateAsync({\n        chainId: targetChainId as (typeof chains)[number][\"id\"],\n      });\n      setStep(\"idle\");\n    } catch (e) {\n      fail(e);\n    }\n  };\n\n  const execute = async (\n    request: { contract: ContractRequest } | { transaction: TransactionRequest },\n  ) => {\n    setError(undefined);\n    setHash(undefined);\n    setStep(\"confirming\");\n    try {\n      // Pin the chain so the wallet can't send on a different one.\n      const txHash =\n        \"contract\" in request\n          ? await write.mutateAsync({\n              chainId: targetChainId,\n              ...request.contract,\n            } as ContractRequest)\n          : await send.mutateAsync({\n              chainId: targetChainId,\n              ...request.transaction,\n            } as TransactionRequest);\n      setHash(txHash);\n      setStep(\"pending\");\n      onSubmitted?.(txHash);\n    } catch (e) {\n      fail(e);\n    }\n  };\n\n  const reset = useCallback(() => {\n    setStep(\"idle\");\n    setHash(undefined);\n    setError(undefined);\n  }, []);\n\n  return {\n    phase,\n    hash,\n    receipt: receipt.data,\n    error: phase === \"error\" ? (error ?? receipt.error ?? undefined) : error,\n    isConnected: connection.status === \"connected\",\n    wrongChain,\n    targetChain,\n    execute,\n    switchToTarget,\n    reset,\n  };\n}\n\n/** Why a call failed, in the contract's own words when it gave a revert reason. */\nexport function revertReason(error: unknown) {\n  if (!(error instanceof BaseError)) {\n    return error instanceof Error ? error.message : \"Something went wrong.\";\n  }\n  const revert = error.walk((e) => e instanceof ContractFunctionRevertedError);\n  if (revert instanceof ContractFunctionRevertedError) {\n    return revert.reason ?? revert.data?.errorName ?? revert.shortMessage;\n  }\n  return error.shortMessage;\n}\n\nexport type SimulationStatus = \"idle\" | \"checking\" | \"ok\" | \"failed\";\n\nexport type UseTransactionSimulationParameters = {\n  /** Contract call to simulate. Pass this or `transaction`. */\n  contract?: ContractRequest;\n  /** Plain transaction to simulate. Pass this or `contract`. */\n  transaction?: TransactionRequest;\n  /** Chain to simulate on. Defaults to the current chain. */\n  chainId?: number;\n  /** Set false to skip the simulation. */\n  enabled?: boolean;\n};\n\n/**\n * Dry-runs a transaction from the connected account with `eth_call`, so a\n * revert shows up before the wallet opens. `status` is `idle` until a wallet\n * is connected. `reason` is set when it would fail.\n */\nexport function useTransactionSimulation({\n  contract,\n  transaction,\n  chainId,\n  enabled = true,\n}: UseTransactionSimulationParameters) {\n  const { address } = useConnection();\n  const on = enabled && Boolean(address);\n  const simulated = useSimulateContract({\n    ...contract,\n    chainId,\n    account: address,\n    query: { enabled: on && Boolean(contract), retry: false },\n  } as never);\n  const called = useCall({\n    ...transaction,\n    chainId,\n    account: address,\n    query: { enabled: on && !contract && Boolean(transaction), retry: false },\n  } as never);\n  const query = contract ? simulated : called;\n\n  const status: SimulationStatus =\n    !on || (!contract && !transaction)\n      ? \"idle\"\n      : query.isError\n        ? \"failed\"\n        : query.isPending\n          ? \"checking\"\n          : \"ok\";\n\n  return {\n    status,\n    reason: status === \"failed\" ? revertReason(query.error) : undefined,\n    error: status === \"failed\" ? query.error : undefined,\n    refetch: query.refetch,\n  };\n}\n\nexport type TransactionButtonProps = Omit<\n  ComponentProps<typeof Button>,\n  \"onClick\" | \"onError\" | \"children\"\n> &\n  TransactionFlowOptions & {\n    /** Contract call to make. Pass this or `transaction`. */\n    contract?: ContractRequest;\n    /** Plain transaction to send. Pass this or `contract`. */\n    transaction?: TransactionRequest;\n    /** Disable the button and show this text, e.g. \"Enter an amount\". Name the blocker, not just \"Disabled\". */\n    disabledReason?: string;\n    /**\n     * Dry-run the transaction first. If it would revert, the button is\n     * disabled and the revert reason is shown, before the wallet opens.\n     */\n    simulate?: boolean;\n    /** Button label. */\n    children?: ReactNode;\n    /** Label after success. */\n    successLabel?: ReactNode;\n    /** Return to idle this long after success, in ms. Pass false to stay. */\n    resetAfter?: number | false;\n    /** Hide the status line under the button. */\n    hideStatus?: boolean;\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\nconst statusText: Partial<Record<TxPhase, string>> = {\n  switching: \"Approve the network switch in your wallet.\",\n  confirming: \"Confirm the transaction in your wallet.\",\n  pending: \"Transaction submitted. Waiting for confirmation…\",\n  success: \"Transaction confirmed.\",\n  cancelled: \"Cancelled in wallet.\",\n};\n\n/**\n * Sends a transaction and shows every step on the button itself. When\n * disconnected it opens the wallet picker. On the wrong network it offers to\n * switch. Each phase gets a label, a status line, and `data-phase` on the\n * root. With `simulate` it dry-runs the call and names the revert reason\n * instead of letting the wallet open on a transaction that will fail.\n */\nexport function TransactionButton({\n  contract,\n  transaction,\n  chainId,\n  confirmations,\n  onSubmitted,\n  onSuccess,\n  onError,\n  disabledReason,\n  simulate = false,\n  children = \"Submit\",\n  successLabel = \"Done\",\n  resetAfter = 4000,\n  hideStatus = false,\n  agentConfirm,\n  disabled,\n  className,\n  ...buttonProps\n}: TransactionButtonProps) {\n  const [connectOpen, setConnectOpen] = useState(false);\n  const flow = useTransactionFlow({\n    chainId,\n    confirmations,\n    onSubmitted,\n    onSuccess,\n    onError,\n  });\n  const { phase, reset } = flow;\n\n  useEffect(() => {\n    if (phase !== \"success\" || resetAfter === false) return;\n    const timer = setTimeout(reset, resetAfter);\n    return () => clearTimeout(timer);\n  }, [phase, resetAfter, reset]);\n\n  const busy = phase === \"switching\" || phase === \"confirming\" || phase === \"pending\";\n\n  const simulation = useTransactionSimulation({\n    contract,\n    transaction,\n    chainId: flow.targetChain?.id,\n    enabled: simulate && !flow.wrongChain && !disabledReason && !busy && phase !== \"success\",\n  });\n  // The transaction just sent may have changed what the next one would do.\n  const resimulate = simulation.refetch;\n  useEffect(() => {\n    if (simulate && (phase === \"success\" || phase === \"reverted\")) resimulate();\n  }, [simulate, phase, resimulate]);\n\n  let label: ReactNode = children;\n  let action: (() => void) | undefined;\n  // In-flight and success states win over `disabledReason`: a form that\n  // clears itself on success shouldn't hide the confirmation.\n  if (!flow.isConnected) {\n    label = \"Connect wallet\";\n    action = () => setConnectOpen(true);\n  } else if (phase === \"switching\") {\n    label = \"Switching network…\";\n  } else if (phase === \"confirming\") {\n    label = \"Confirm in wallet…\";\n  } else if (phase === \"pending\") {\n    label = \"Pending…\";\n  } else if (phase === \"success\") {\n    label = successLabel;\n  } else if (disabledReason) {\n    label = disabledReason;\n  } else if (flow.wrongChain) {\n    label = `Switch to ${flow.targetChain?.name ?? \"the right network\"}`;\n    action = flow.switchToTarget;\n  } else if (simulation.status === \"checking\") {\n    label = \"Checking…\";\n  } else if (simulation.status === \"failed\") {\n    label = \"Transaction will fail\";\n  } else if (contract) {\n    action = () => flow.execute({ contract });\n  } else if (transaction) {\n    action = () => flow.execute({ transaction });\n  }\n\n  const message =\n    phase === \"reverted\"\n      ? \"Transaction reverted. Nothing changed except the gas fee.\"\n      : phase === \"error\"\n        ? ((flow.error as { shortMessage?: string } | undefined)?.shortMessage ??\n          flow.error?.message ??\n          \"Something went wrong.\")\n        : simulation.status === \"failed\"\n          ? `This transaction would fail: ${simulation.reason}`\n          : undefined;\n\n  return (\n    <div\n      data-slot=\"transaction-button\"\n      data-phase={phase}\n      data-error={errorCode(phase, flow.error)}\n      className={cn(\"inline-flex flex-col gap-2\", className)}\n    >\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 a transaction on ${flow.targetChain?.name ?? \"the selected network\"} from your wallet`,\n              ))\n        }\n      >\n        {busy && <Loader2Icon aria-hidden className=\"animate-spin\" />}\n        {phase === \"success\" && <CheckIcon aria-hidden />}\n        <MorphText>{label}</MorphText>\n      </Button>\n      {!hideStatus && (\n        <>\n          <p role=\"status\" className=\"text-sm text-muted-foreground empty:hidden\">\n            {statusText[phase] ?? \"\"}\n          </p>\n          {message && (\n            <p role=\"alert\" className=\"text-sm text-destructive\">\n              {message}\n            </p>\n          )}\n        </>\n      )}\n      <ConnectWalletDialog open={connectOpen} onOpenChange={setConnectOpen} />\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "docs": "Docs: https://0xui.io/components/transaction-button.md",
  "categories": [
    "transactions"
  ],
  "type": "registry:component"
}