{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "transaction-history",
  "title": "Transaction History",
  "description": "Transactions sent from this app with live status, persisted in localStorage (synced across tabs, 50 max). Call recordTransaction({ hash, chainId, from, description }) from anywhere (e.g. TransactionButton onSubmitted); pending rows poll for receipts and keep their final status. Filters to the connected account by default. Pass transactions from an indexer (transactions prop) for cross-device history. Paginated with Show more. Exports useTransactionHistory, recordTransaction, updateTransaction and clearTransactionHistory.",
  "dependencies": [
    "wagmi",
    "viem",
    "lucide-react"
  ],
  "registryDependencies": [
    "button",
    "@0xui/explorer-link",
    "@0xui/transaction-status",
    "@0xui/0xui-utils"
  ],
  "files": [
    {
      "path": "registry/default/components/transaction-history.tsx",
      "content": "// Docs: https://0xui.io/components/transaction-history.md\nimport { CheckIcon, Loader2Icon, XIcon } from \"lucide-react\";\nimport { useEffect, useState, useSyncExternalStore, type ReactNode } from \"react\";\nimport type { Address, Hash } from \"viem\";\nimport { useConnection } from \"wagmi\";\nimport { ExplorerLink } from \"@/components/explorer-link\";\nimport { useMinedReceipt } from \"@/components/transaction-status\";\nimport { Button } from \"@/components/ui/button\";\nimport { truncateAddress } from \"@/lib/0xui-utils\";\nimport { cn } from \"@/lib/utils\";\n\nexport type HistoryStatus = \"pending\" | \"confirmed\" | \"reverted\";\n\nexport type HistoryEntry = {\n  hash: Hash;\n  chainId: number;\n  /** Sender, so the list can show only the connected account's transactions. */\n  from?: Address;\n  /** What the transaction did, e.g. \"Swap 1 ETH for USDC\". */\n  description?: string;\n  /** Unix time in ms. */\n  submittedAt: number;\n  /** Stored once the transaction settles, so it isn't polled again. */\n  status: HistoryStatus;\n};\n\nconst STORAGE_KEY = \"0xui:transactions\";\nconst LIMIT = 50;\nconst EMPTY: HistoryEntry[] = [];\nconst listeners = new Set<() => void>();\nlet cache: HistoryEntry[] | undefined;\n\nfunction load(): HistoryEntry[] {\n  if (cache) return cache;\n  try {\n    cache = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? \"[]\");\n  } catch {\n    cache = [];\n  }\n  return cache!;\n}\n\nfunction save(entries: HistoryEntry[]) {\n  cache = entries.slice(0, LIMIT);\n  try {\n    localStorage.setItem(STORAGE_KEY, JSON.stringify(cache));\n  } catch {\n    // Storage blocked or full: history lasts for this page only.\n  }\n  listeners.forEach((listener) => listener());\n}\n\nfunction subscribe(listener: () => void) {\n  listeners.add(listener);\n  // Other tabs.\n  const onStorage = (e: StorageEvent) => {\n    if (e.key !== STORAGE_KEY) return;\n    cache = undefined;\n    listener();\n  };\n  window.addEventListener(\"storage\", onStorage);\n  return () => {\n    listeners.delete(listener);\n    window.removeEventListener(\"storage\", onStorage);\n  };\n}\n\n/**\n * Add a transaction to the history. Call it from anywhere, e.g. a\n * TransactionButton's `onSubmitted`. Re-recording a hash updates it.\n */\nexport function recordTransaction(\n  entry: Omit<HistoryEntry, \"submittedAt\" | \"status\"> &\n    Partial<Pick<HistoryEntry, \"submittedAt\" | \"status\">>\n) {\n  const rest = load().filter((e) => e.hash !== entry.hash);\n  save([{ submittedAt: Date.now(), status: \"pending\", ...entry }, ...rest]);\n}\n\nexport function updateTransaction(hash: Hash, update: Partial<HistoryEntry>) {\n  save(load().map((e) => (e.hash === hash ? { ...e, ...update } : e)));\n}\n\nexport function clearTransactionHistory() {\n  save([]);\n}\n\n/** Recorded transactions, newest first. Pass `from` to keep only one account's. */\nexport function useTransactionHistory({ from }: { from?: Address } = {}) {\n  const entries = useSyncExternalStore(subscribe, load, () => EMPTY);\n  const transactions = from\n    ? entries.filter((e) => !e.from || e.from.toLowerCase() === from.toLowerCase())\n    : entries;\n  return {\n    transactions,\n    record: recordTransaction,\n    clear: clearTransactionHistory,\n  };\n}\n\nconst relative = (ms: number, locale?: string) => {\n  const seconds = Math.round((ms - Date.now()) / 1000);\n  const format = new Intl.RelativeTimeFormat(locale, { numeric: \"auto\" });\n  const abs = Math.abs(seconds);\n  if (abs < 60) return format.format(seconds, \"second\");\n  if (abs < 3600) return format.format(Math.round(seconds / 60), \"minute\");\n  if (abs < 86400) return format.format(Math.round(seconds / 3600), \"hour\");\n  return format.format(Math.round(seconds / 86400), \"day\");\n};\n\nfunction HistoryRow({ entry, locale }: { entry: HistoryEntry; locale?: string }) {\n  // Only pending transactions are polled. Settled ones keep their stored status.\n  const receipt = useMinedReceipt({\n    hash: entry.status === \"pending\" ? entry.hash : undefined,\n    chainId: entry.chainId,\n  });\n  useEffect(() => {\n    if (receipt.data) {\n      updateTransaction(entry.hash, {\n        status: receipt.data.status === \"success\" ? \"confirmed\" : \"reverted\",\n      });\n    }\n  }, [receipt.data, entry.hash]);\n\n  // Entries from an indexer aren't in the local store, so derive the status too.\n  const status: HistoryStatus =\n    entry.status === \"pending\" && receipt.data\n      ? receipt.data.status === \"success\"\n        ? \"confirmed\"\n        : \"reverted\"\n      : entry.status;\n  return (\n    <li data-status={status} className=\"flex items-center gap-3 py-2 text-sm\">\n      {status === \"pending\" ? (\n        <Loader2Icon aria-label=\"Pending\" className=\"size-4 shrink-0 animate-spin text-muted-foreground\" />\n      ) : status === \"confirmed\" ? (\n        <CheckIcon aria-label=\"Confirmed\" className=\"size-4 shrink-0 text-emerald-500\" />\n      ) : (\n        <XIcon aria-label=\"Reverted\" className=\"size-4 shrink-0 text-destructive\" />\n      )}\n      <span className=\"flex min-w-0 flex-1 flex-col\">\n        <span className=\"truncate\">\n          {entry.description ?? <span className=\"font-mono\">{truncateAddress(entry.hash, { start: 10, end: 8 })}</span>}\n        </span>\n        <span className=\"text-xs text-muted-foreground\">\n          <time dateTime={new Date(entry.submittedAt).toISOString()}>{relative(entry.submittedAt, locale)}</time>\n          {status === \"reverted\" && \" · Reverted\"}\n        </span>\n      </span>\n      <ExplorerLink tx={entry.hash} chainId={entry.chainId} className=\"shrink-0 text-xs text-muted-foreground\">\n        View\n      </ExplorerLink>\n    </li>\n  );\n}\n\nexport type TransactionHistoryProps = {\n  /** Show only this account's transactions. Defaults to the connected account. Pass null for everyone's. */\n  from?: Address | null;\n  /**\n   * Transactions from your own source, e.g. an indexer, instead of the ones\n   * recorded in this browser. Pending entries still update live.\n   */\n  transactions?: readonly HistoryEntry[];\n  /** Rows per page, with \"Show more\" for the rest. */\n  pageSize?: number;\n  /** Show a \"Clear\" button. */\n  clearable?: boolean;\n  title?: ReactNode;\n  locale?: string;\n  className?: string;\n};\n\n/**\n * Transactions sent from this app, newest first, with live status. Stored in\n * this browser (localStorage), so it's per device. Record entries with\n * `recordTransaction`.\n */\nexport function TransactionHistory({\n  from: fromProp,\n  transactions: transactionsProp,\n  pageSize = 10,\n  clearable = true,\n  title = \"Recent transactions\",\n  locale,\n  className,\n}: TransactionHistoryProps) {\n  const { address } = useConnection();\n  const from = fromProp === null ? undefined : (fromProp ?? address);\n  const local = useTransactionHistory({ from });\n  const transactions = transactionsProp ?? local.transactions;\n  const [visible, setVisible] = useState(pageSize);\n  const shown = transactions.slice(0, visible);\n\n  return (\n    <section\n      data-slot=\"transaction-history\"\n      aria-label={typeof title === \"string\" ? title : \"Recent transactions\"}\n      className={cn(\"flex flex-col gap-2 rounded-2xl border p-4\", className)}\n    >\n      <header className=\"flex items-center justify-between gap-2\">\n        {title && <h3 className=\"font-semibold\">{title}</h3>}\n        {clearable && !transactionsProp && shown.length > 0 && (\n          <Button variant=\"ghost\" size=\"xs\" onClick={local.clear}>\n            Clear\n          </Button>\n        )}\n      </header>\n      {shown.length === 0 ? (\n        <p className=\"py-4 text-center text-sm text-muted-foreground\">\n          Transactions you send will show up here.\n        </p>\n      ) : (\n        <ul className=\"flex flex-col divide-y\">\n          {shown.map((entry) => (\n            <HistoryRow key={entry.hash} entry={entry} locale={locale} />\n          ))}\n        </ul>\n      )}\n      {transactions.length > visible && (\n        <button\n          type=\"button\"\n          onClick={() => setVisible((v) => v + pageSize)}\n          className=\"self-center rounded-md px-3 py-1.5 text-sm font-medium hover:bg-muted\"\n        >\n          Show more ({transactions.length - visible})\n        </button>\n      )}\n    </section>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "docs": "Docs: https://0xui.io/components/transaction-history.md",
  "categories": [
    "transactions"
  ],
  "type": "registry:component"
}