{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "contract-form",
  "title": "Contract Form",
  "description": "Read/write forms for any contract generated from its ABI: one collapsible card per function with typed inputs (range-checked ints, checksummed addresses, sized bytes, bool select, JSON arrays/tuples), Read with formatted results for view functions, TransactionButton for writes (plus an ETH value field when payable) naming the first invalid field. Filter with functions=[...] or show=read|write. Exports ContractFunction, parseAbiInput and formatAbiValue.",
  "dependencies": [
    "viem",
    "wagmi",
    "@tanstack/react-query"
  ],
  "registryDependencies": [
    "button",
    "@0xui/transaction-button",
    "@0xui/morph-text"
  ],
  "files": [
    {
      "path": "registry/default/components/contract-form.tsx",
      "content": "// Docs: https://0xui.io/components/contract-form.md\nimport { useMutation } from \"@tanstack/react-query\";\nimport { useId, useMemo, useState } from \"react\";\nimport {\n  getAddress,\n  isAddress,\n  isHex,\n  parseEther,\n  size,\n  type Abi,\n  type AbiFunction,\n  type AbiParameter,\n  type Address,\n} from \"viem\";\nimport { usePublicClient } from \"wagmi\";\nimport { MorphText } from \"@/components/morph-text\";\nimport { TransactionButton, type ContractRequest } from \"@/components/transaction-button\";\nimport { Button } from \"@/components/ui/button\";\nimport { cn } from \"@/lib/utils\";\n\ntype Parsed = { value: unknown; error?: undefined } | { value?: undefined; error: string };\n\nfunction intBounds(type: string) {\n  const signed = type.startsWith(\"int\");\n  const bits = BigInt(type.replace(/^u?int/, \"\") || \"256\");\n  return signed\n    ? { min: -(2n ** (bits - 1n)), max: 2n ** (bits - 1n) - 1n }\n    : { min: 0n, max: 2n ** bits - 1n };\n}\n\n/** Turn an already-parsed JSON value into the shape viem expects for `param`. */\nfunction coerce(param: AbiParameter, value: unknown): unknown {\n  const array = param.type.match(/^(.*)\\[(\\d*)\\]$/);\n  if (array) {\n    if (!Array.isArray(value)) throw new Error(\"Expected a JSON array\");\n    if (array[2] && value.length !== Number(array[2])) throw new Error(`Expected ${array[2]} items`);\n    return value.map((item) => coerce({ ...param, type: array[1]! }, item));\n  }\n  if (param.type === \"tuple\") {\n    const components = (param as { components: readonly AbiParameter[] }).components;\n    if (Array.isArray(value)) return components.map((c, i) => coerce(c, value[i]));\n    if (value && typeof value === \"object\")\n      return Object.fromEntries(\n        components.map((c, i) => [c.name ?? i, coerce(c, (value as Record<string, unknown>)[c.name ?? i])])\n      );\n    throw new Error(\"Expected a JSON object or array\");\n  }\n  const parsed = parseAbiInput(param, typeof value === \"string\" ? value : JSON.stringify(value));\n  if (parsed.error) throw new Error(parsed.error);\n  return parsed.value;\n}\n\n/**\n * Parse text from a form field into a value for an ABI parameter. Integers\n * become bigints (range-checked), addresses are checksummed, bytes are\n * length-checked, and arrays and tuples are entered as JSON.\n */\nexport function parseAbiInput(param: AbiParameter, raw: string): Parsed {\n  const text = raw.trim();\n  const type = param.type;\n  try {\n    if (type.endsWith(\"]\") || type === \"tuple\") {\n      if (!text) return { error: \"Required\" };\n      return { value: coerce(param, JSON.parse(text)) };\n    }\n    if (type === \"string\") return { value: raw };\n    if (!text) return { error: \"Required\" };\n    if (/^u?int\\d*$/.test(type)) {\n      if (!/^-?\\d+$/.test(text.replace(/_/g, \"\"))) return { error: \"Whole number\" };\n      const value = BigInt(text.replace(/_/g, \"\"));\n      const { min, max } = intBounds(type);\n      if (value < min || value > max) return { error: `Out of range for ${type}` };\n      return { value };\n    }\n    if (type === \"address\") {\n      if (!isAddress(text, { strict: false })) return { error: \"Not an address\" };\n      if (!isAddress(text)) return { error: \"Checksum doesn't match\" };\n      return { value: getAddress(text) };\n    }\n    if (type === \"bool\") {\n      if (text === \"true\") return { value: true };\n      if (text === \"false\") return { value: false };\n      return { error: \"true or false\" };\n    }\n    if (type.startsWith(\"bytes\")) {\n      if (!isHex(text)) return { error: \"Hex, starting with 0x\" };\n      const fixed = type.slice(5);\n      if (fixed && size(text) !== Number(fixed)) return { error: `Exactly ${fixed} bytes` };\n      return { value: text };\n    }\n    return { error: `Unsupported type ${type}` };\n  } catch (e) {\n    return { error: e instanceof Error ? e.message : \"Invalid JSON\" };\n  }\n}\n\n/** Readable text for a contract return value: bigints as digits, nested values as JSON. */\nexport function formatAbiValue(value: unknown): string {\n  if (typeof value === \"bigint\") return value.toString();\n  if (typeof value === \"string\" || typeof value === \"boolean\") return String(value);\n  return JSON.stringify(\n    value,\n    (_, v) => (typeof v === \"bigint\" ? v.toString() : v),\n    2\n  );\n}\n\nconst isRead = (fn: AbiFunction) =>\n  fn.stateMutability === \"view\" || fn.stateMutability === \"pure\";\n\nfunction signature(fn: AbiFunction) {\n  return `${fn.name}(${fn.inputs.map((i) => i.type).join(\", \")})`;\n}\n\nexport type ContractFunctionProps = {\n  address: Address;\n  fn: AbiFunction;\n  chainId?: number;\n  /** Start expanded. */\n  defaultOpen?: boolean;\n};\n\n/** One ABI function as a form: an input per parameter, then Read or a TransactionButton. */\nexport function ContractFunction({ address, fn, chainId, defaultOpen = false }: ContractFunctionProps) {\n  const id = useId();\n  const client = usePublicClient({ chainId });\n  const [values, setValues] = useState<string[]>(() => fn.inputs.map((i) => (i.type === \"bool\" ? \"false\" : \"\")));\n  const [ethValue, setEthValue] = useState(\"\");\n  const [touched, setTouched] = useState(false);\n\n  const parsed = fn.inputs.map((input, i) => parseAbiInput(input, values[i] ?? \"\"));\n  const args = parsed.map((p) => p.value);\n  const firstError = parsed.findIndex((p) => p.error);\n  const payable = fn.stateMutability === \"payable\";\n  const value = (() => {\n    if (!payable || !ethValue.trim()) return undefined;\n    try {\n      return parseEther(ethValue.trim());\n    } catch {\n      return null;\n    }\n  })();\n\n  const read = useMutation({\n    mutationFn: () =>\n      client!.readContract({ address, abi: [fn], functionName: fn.name, args }),\n  });\n\n  const blocker =\n    firstError >= 0\n      ? `Check ${fn.inputs[firstError]!.name || `argument ${firstError + 1}`}`\n      : value === null\n        ? \"Check the ETH value\"\n        : undefined;\n\n  return (\n    <details\n      data-slot=\"contract-function\"\n      open={defaultOpen || undefined}\n      className=\"group rounded-xl border\"\n    >\n      <summary className=\"flex cursor-pointer list-none items-center gap-2 px-4 py-3 text-sm\">\n        <span\n          className={cn(\n            \"rounded px-1.5 py-0.5 text-xs font-medium\",\n            isRead(fn) ? \"bg-sky-500/15 text-sky-700 dark:text-sky-300\" : payable ? \"bg-amber-500/15 text-amber-700 dark:text-amber-300\" : \"bg-violet-500/15 text-violet-700 dark:text-violet-300\"\n          )}\n        >\n          {isRead(fn) ? \"read\" : payable ? \"payable\" : \"write\"}\n        </span>\n        <code className=\"truncate font-mono\">{signature(fn)}</code>\n        {fn.outputs.length > 0 && (\n          <span className=\"ml-auto shrink-0 font-mono text-xs text-muted-foreground\">\n            → {fn.outputs.map((o) => o.type).join(\", \")}\n          </span>\n        )}\n      </summary>\n      <form\n        className=\"flex flex-col gap-3 border-t px-4 py-3\"\n        onSubmit={(e) => {\n          e.preventDefault();\n          setTouched(true);\n          if (isRead(fn) && !blocker) read.mutate();\n        }}\n      >\n        {fn.inputs.map((input, i) => {\n          const fieldId = `${id}-${i}`;\n          const error = touched || values[i] ? parsed[i]!.error : undefined;\n          const complex = input.type.endsWith(\"]\") || input.type === \"tuple\";\n          return (\n            <div key={i} className=\"flex flex-col gap-1\">\n              <label htmlFor={fieldId} className=\"text-xs text-muted-foreground\">\n                {input.name || `arg${i}`} <code className=\"font-mono\">{input.type}</code>\n              </label>\n              {input.type === \"bool\" ? (\n                <select\n                  id={fieldId}\n                  value={values[i]}\n                  onChange={(e) => setValues((v) => v.map((x, j) => (j === i ? e.target.value : x)))}\n                  className=\"h-9 rounded-md border bg-background px-2 text-sm\"\n                >\n                  <option value=\"false\">false</option>\n                  <option value=\"true\">true</option>\n                </select>\n              ) : complex ? (\n                <textarea\n                  id={fieldId}\n                  rows={3}\n                  spellCheck={false}\n                  placeholder={input.type === \"tuple\" ? '{ \"field\": \"value\" }' : '[\"…\"]'}\n                  aria-invalid={Boolean(error) || undefined}\n                  value={values[i]}\n                  onChange={(e) => setValues((v) => v.map((x, j) => (j === i ? e.target.value : x)))}\n                  className=\"rounded-md border bg-background px-2 py-1.5 font-mono text-sm aria-invalid:border-destructive\"\n                />\n              ) : (\n                <input\n                  id={fieldId}\n                  type=\"text\"\n                  spellCheck={false}\n                  autoComplete=\"off\"\n                  inputMode={/int/.test(input.type) ? \"numeric\" : undefined}\n                  placeholder={input.type}\n                  aria-invalid={Boolean(error) || undefined}\n                  value={values[i]}\n                  onChange={(e) => setValues((v) => v.map((x, j) => (j === i ? e.target.value : x)))}\n                  className=\"h-9 rounded-md border bg-background px-2 font-mono text-sm aria-invalid:border-destructive\"\n                />\n              )}\n              {error && <span className=\"text-xs text-destructive\">{error}</span>}\n            </div>\n          );\n        })}\n\n        {payable && (\n          <div className=\"flex flex-col gap-1\">\n            <label htmlFor={`${id}-value`} className=\"text-xs text-muted-foreground\">\n              Value <code className=\"font-mono\">ETH</code>\n            </label>\n            <input\n              id={`${id}-value`}\n              type=\"text\"\n              inputMode=\"decimal\"\n              placeholder=\"0\"\n              aria-invalid={value === null || undefined}\n              value={ethValue}\n              onChange={(e) => setEthValue(e.target.value)}\n              className=\"h-9 rounded-md border bg-background px-2 font-mono text-sm aria-invalid:border-destructive\"\n            />\n          </div>\n        )}\n\n        {isRead(fn) ? (\n          <>\n            <Button type=\"submit\" variant=\"outline\" size=\"sm\" className=\"self-start\" disabled={read.isPending}>\n              <MorphText>{read.isPending ? \"Reading…\" : \"Read\"}</MorphText>\n            </Button>\n            {read.isSuccess && (\n              <pre aria-label=\"Result\" className=\"overflow-auto rounded-lg bg-muted/50 p-3 font-mono text-xs\">\n                {formatAbiValue(read.data)}\n              </pre>\n            )}\n            {read.isError && (\n              <p role=\"alert\" className=\"text-sm text-destructive\">\n                {(read.error as { shortMessage?: string }).shortMessage ?? read.error.message}\n              </p>\n            )}\n          </>\n        ) : (\n          <TransactionButton\n            chainId={chainId}\n            contract={\n              blocker\n                ? undefined\n                : // The ABI is only known at runtime, so wagmi can't type-check this call.\n                  ({ address, abi: [fn], functionName: fn.name, args, value: value ?? undefined } as ContractRequest)\n            }\n            disabledReason={\n              blocker && (touched || values.some((v) => v.trim()) ? blocker : \"Fill in the fields\")\n            }\n            size=\"sm\"\n            className=\"self-start\"\n          >\n            {fn.name}\n          </TransactionButton>\n        )}\n      </form>\n    </details>\n  );\n}\n\nexport type ContractFormProps = {\n  address: Address;\n  abi: Abi;\n  chainId?: number;\n  /** Only these function names, in this order. */\n  functions?: readonly string[];\n  /** Show read functions, write functions, or both. */\n  show?: \"all\" | \"read\" | \"write\";\n  className?: string;\n};\n\n/**\n * Interactive forms for a contract, generated from its ABI: one card per\n * function with typed inputs, Read for view functions, and a\n * TransactionButton for writes. Handy for admin panels, debugging, and\n * agent-built tools.\n */\nexport function ContractForm({ address, abi, chainId, functions, show = \"all\", className }: ContractFormProps) {\n  const fns = useMemo(() => {\n    const all = abi.filter((item): item is AbiFunction => item.type === \"function\");\n    const picked = functions\n      ? functions.flatMap((name) => all.filter((fn) => fn.name === name))\n      : all;\n    return picked.filter((fn) => (show === \"read\" ? isRead(fn) : show === \"write\" ? !isRead(fn) : true));\n  }, [abi, functions, show]);\n\n  return (\n    <div data-slot=\"contract-form\" className={cn(\"flex flex-col gap-2\", className)}>\n      {fns.length === 0 ? (\n        <p className=\"text-sm text-muted-foreground\">No matching functions in this ABI.</p>\n      ) : (\n        fns.map((fn, i) => (\n          <ContractFunction key={`${signature(fn)}-${i}`} address={address} fn={fn} chainId={chainId} />\n        ))\n      )}\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "docs": "Docs: https://0xui.io/components/contract-form.md",
  "categories": [
    "transactions"
  ],
  "type": "registry:component"
}