{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "portfolio",
  "title": "Portfolio",
  "description": "Token holdings block: total fiat value on top, then rows (icon, name, amount, value) sorted by value, for the connected account or any address. Balances for the whole token list are read in one batch; prices are a prop, keyed by chainId:address, address or symbol. Spam filtering: likely spam (looksLikeSpam or your own isSpam, e.g. scanner verdicts), tokens without a price and dust under minValue are collapsed under a Hidden tokens disclosure with the reason, and left out of the total. Pagination (pageSize with Show more). Accepts balances from an indexer (balances prop) instead of RPC reads. Loading skeleton measured from the real layout (skullet): from sample rows over RPC, or from your own data's exact shape when isLoading is set, so nothing moves on reveal. Empty, error and disconnected states. locale prop for server rendering. Exports usePortfolio and hiddenReason. Takes holdings from an indexer with their own token metadata; tokens off the list are hidden as 'Not on the token list' unless showUnlisted is set.",
  "dependencies": [
    "wagmi",
    "viem",
    "lucide-react",
    "skullet"
  ],
  "registryDependencies": [
    "@0xui/token-select",
    "@0xui/token-icon",
    "@0xui/token-amount",
    "@0xui/morph-text",
    "@0xui/token-list"
  ],
  "files": [
    {
      "path": "registry/default/components/portfolio.tsx",
      "content": "// Docs: https://0xui.io/blocks/portfolio.md\nimport { ChevronDownIcon } from \"lucide-react\";\nimport { useId, useMemo, useState, type ReactNode } from \"react\";\nimport { Skeleton, SkeletonBox } from \"skullet/react\";\nimport { formatUnits, type Address } from \"viem\";\nimport { useChainId, useConnection } from \"wagmi\";\nimport { MorphText } from \"@/components/morph-text\";\nimport { TokenAmount } from \"@/components/token-amount\";\nimport { TokenIcon } from \"@/components/token-icon\";\nimport { useTokenBalances, type Token } from \"@/components/token-select\";\nimport { getTokenPrice, isNativeToken, looksLikeSpam, type TokenPrices } from \"@/lib/token-list\";\nimport { cn } from \"@/lib/utils\";\n\n/** Why a holding is tucked under \"Hidden tokens\". */\nexport type HiddenReason = \"spam\" | \"unlisted\" | \"unpriced\" | \"dust\";\n\nexport type PortfolioRow = {\n  token: Token;\n  balance: bigint;\n  /** Fiat value, when a price is known. */\n  value: number | undefined;\n  /** The token came from `holdings` and isn't on the token list. */\n  unlisted?: boolean;\n  /** Set when the row is hidden. */\n  hidden?: HiddenReason;\n};\n\n/** A holding from your own source, with the token's metadata as that source reports it. */\nexport type PortfolioHolding = { token: Token; balance: bigint };\n\nexport type PortfolioFilters = {\n  /**\n   * Flags scam tokens. Defaults to `looksLikeSpam`. Pass your own to add\n   * verdicts from a scanning service or your indexer, e.g.\n   * `(t) => looksLikeSpam(t) || flagged.has(t.address)`.\n   */\n  isSpam?: (token: Token) => boolean;\n  /**\n   * Show `holdings` whose token isn't on the token list. Off by default: the\n   * list is the allowlist, and an indexer returns every token an address\n   * was ever sent.\n   */\n  showUnlisted?: boolean;\n  /** Hide tokens without a price. Most airdropped spam has no market. */\n  hideUnpriced?: boolean;\n  /** Hide holdings worth less than this, in your currency. */\n  minValue?: number;\n};\n\n/** Hidden reason for a holding, or undefined to show it. The native currency is always shown. */\nexport function hiddenReason(\n  row: Omit<PortfolioRow, \"hidden\">,\n  { isSpam = looksLikeSpam, showUnlisted = false, hideUnpriced = true, minValue = 0.5 }: PortfolioFilters = {}\n): HiddenReason | undefined {\n  if (isNativeToken(row.token)) return undefined;\n  if (isSpam(row.token)) return \"spam\";\n  if (row.unlisted && !showUnlisted) return \"unlisted\";\n  if (row.value === undefined) return hideUnpriced ? \"unpriced\" : undefined;\n  if (row.value < minValue) return \"dust\";\n  return undefined;\n}\n\nconst byValue = (a: PortfolioRow, b: PortfolioRow) =>\n  (b.value ?? -1) - (a.value ?? -1) ||\n  Number(formatUnits(b.balance, b.token.decimals)) - Number(formatUnits(a.balance, a.token.decimals));\n\n/**\n * Holdings for a token list, valued with `prices` and sorted by value, then\n * by amount for tokens without a price. Likely spam, unpriced tokens and\n * dust go to `hidden` rather than `rows`, so the total isn't inflated and\n * nothing is lost: show them on request.\n *\n * Pass `holdings` when your indexer returns tokens with their own metadata.\n * Tokens on the list keep the list's metadata. The rest are hidden as\n * `unlisted` unless `showUnlisted` is set.\n */\nexport function usePortfolio({\n  tokens = noTokens,\n  prices = {},\n  address,\n  chainId: chainIdProp,\n  hideZero = true,\n  balances: balancesProp,\n  holdings,\n  isSpam,\n  showUnlisted,\n  hideUnpriced,\n  minValue,\n}: {\n  tokens?: readonly Token[];\n  prices?: TokenPrices;\n  address?: Address;\n  chainId?: number;\n  hideZero?: boolean;\n  /** Balances from your own source (e.g. an indexer), keyed by token address. Skips RPC reads. */\n  balances?: ReadonlyMap<string, bigint> | Record<string, bigint>;\n  /** Holdings from your own source, each with its token's metadata. Skips RPC reads and wins over `balances`. */\n  holdings?: readonly PortfolioHolding[];\n} & PortfolioFilters) {\n  const currentChainId = useChainId();\n  const chainId = chainIdProp ?? currentChainId;\n  const onChain = useMemo(() => tokens.filter((t) => t.chainId === chainId), [tokens, chainId]);\n  const external = Boolean(balancesProp || holdings);\n  const rpc = useTokenBalances(onChain, { chainId, address, enabled: !external });\n  const balances = useMemo(() => {\n    if (!balancesProp) return rpc.balances;\n    const entries = balancesProp instanceof Map ? [...balancesProp] : Object.entries(balancesProp);\n    return new Map(entries.map(([key, value]) => [key.toLowerCase(), value]));\n  }, [balancesProp, rpc.balances]);\n  const isLoading = !external && rpc.isLoading;\n  const isError = !external && rpc.isError;\n\n  const { rows, hidden } = useMemo(() => {\n    const listed = new Map(onChain.map((token) => [token.address.toLowerCase(), token]));\n    const held = holdings\n      ? holdings\n          .filter((holding) => holding.token.chainId === chainId)\n          .map(({ token, balance }) => {\n            // The list's name and logo are the trusted ones.\n            const known = listed.get(token.address.toLowerCase());\n            return { token: known ?? token, balance, unlisted: !known };\n          })\n      : onChain.map((token) => ({\n          token,\n          balance: balances.get(token.address.toLowerCase()) ?? 0n,\n          unlisted: false,\n        }));\n    const all: PortfolioRow[] = held\n      .map((row) => {\n        const price = getTokenPrice(prices, row.token);\n        const value =\n          price === undefined ? undefined : Number(formatUnits(row.balance, row.token.decimals)) * price;\n        return { ...row, value };\n      })\n      .filter((row) => !hideZero || row.balance > 0n)\n      .map((row) => ({\n        ...row,\n        hidden: hiddenReason(row, { isSpam, showUnlisted, hideUnpriced, minValue }),\n      }))\n      .sort(byValue);\n    return { rows: all.filter((row) => !row.hidden), hidden: all.filter((row) => row.hidden) };\n  }, [onChain, chainId, balances, holdings, prices, hideZero, isSpam, showUnlisted, hideUnpriced, minValue]);\n\n  const total = rows.reduce((sum, row) => sum + (row.value ?? 0), 0);\n  const unpriced = rows.filter((row) => row.value === undefined).length;\n\n  return { rows, hidden, total, unpriced, isLoading, isError };\n}\n\nconst noTokens: readonly Token[] = [];\nconst noHoldings: readonly PortfolioHolding[] = [];\n\nexport type PortfolioProps = PortfolioFilters & {\n  /** Tokens to show. With `holdings`, the allowlist: holdings off it are hidden unless `showUnlisted`. */\n  tokens?: readonly Token[];\n  /** Prices keyed by `chainId:address`, address or symbol. Tokens without one are hidden by default. */\n  prices?: TokenPrices;\n  /** Whose holdings. Defaults to the connected account. */\n  address?: Address;\n  chainId?: number;\n  /** Hide tokens with a zero balance. */\n  hideZero?: boolean;\n  currency?: string;\n  /** BCP 47 locale for amounts and values. Defaults to the runtime locale; set it when rendering on a server. */\n  locale?: string;\n  /** Balances from your own source, e.g. an indexer. See usePortfolio. */\n  balances?: ReadonlyMap<string, bigint> | Record<string, bigint>;\n  /** Holdings from your own source, each with its token's metadata. See usePortfolio. */\n  holdings?: readonly PortfolioHolding[];\n  /**\n   * Your own `balances` or `holdings` are still loading, e.g. `query.isLoading`.\n   * Shows the skeleton and skips RPC reads. Set over data you already have\n   * (a refetch), the skeleton takes that data's exact shape.\n   */\n  isLoading?: boolean;\n  /** Rows per page, with \"Show more\" for the rest. */\n  pageSize?: number;\n  title?: ReactNode;\n  className?: string;\n};\n\nfunction ShowMore({ remaining, onClick }: { remaining: number; onClick: () => void }) {\n  return (\n    <button\n      type=\"button\"\n      onClick={onClick}\n      className=\"self-center rounded-md px-3 py-1.5 text-sm font-medium hover:bg-muted\"\n    >\n      Show more ({remaining})\n    </button>\n  );\n}\n\n/** SkeletonBox is a block by default. This one sits in a line of text. */\nconst inlineBox = { display: \"inline-block\", verticalAlign: \"middle\" } as const;\n\n/** Stand-in rows the loading skeleton is measured from. Never shown as text. */\nconst sampleRow = (index: number, name: string, balance: bigint, value: number): PortfolioRow => ({\n  token: {\n    chainId: 0,\n    address: `0x${String(index).padStart(40, \"0\")}`,\n    name,\n    symbol: \"TKN\",\n    decimals: 18,\n  },\n  balance,\n  value,\n});\nconst sampleRows = [\n  sampleRow(1, \"Sample token\", 1_234_500_000_000_000_000n, 3210.55),\n  sampleRow(2, \"Another token\", 250_000_000_000_000_000_000n, 250.1),\n  sampleRow(3, \"Third one\", 4_200_000_000_000_000_000n, 42.07),\n];\n\nfunction Holding({\n  row,\n  money,\n  locale,\n  note,\n}: {\n  row: PortfolioRow;\n  money: Intl.NumberFormat;\n  locale?: string;\n  note?: string;\n}) {\n  const { token, balance, value } = row;\n  return (\n    <li data-hidden={row.hidden} className=\"flex items-center gap-3 py-2\">\n      {/* Spam logos can be offensive or link to scams: letters only. */}\n      <TokenIcon symbol={token.symbol} src={row.hidden === \"spam\" ? undefined : token.logoURI} size={32} />\n      <span className=\"flex min-w-0 flex-1 flex-col\">\n        <span className=\"truncate text-sm font-medium\">{token.name}</span>\n        <TokenAmount\n          value={balance}\n          decimals={token.decimals}\n          symbol={token.symbol}\n          locale={locale}\n          className=\"truncate text-xs text-muted-foreground\"\n        />\n      </span>\n      <span className=\"flex shrink-0 flex-col items-end text-sm tabular-nums\">\n        {value === undefined ? <span className=\"text-muted-foreground\">—</span> : money.format(value)}\n        {note && <span className=\"text-xs text-muted-foreground\">{note}</span>}\n      </span>\n    </li>\n  );\n}\n\n/**\n * Token holdings list: total value on top, then one row per token with\n * amount and value, largest first. Likely spam, tokens without a price and\n * dust are collapsed under \"Hidden tokens\", out of the total. Shows a skeleton\n * measured from sample rows while loading and an empty state when there's nothing to show.\n */\nexport function Portfolio({\n  tokens,\n  prices,\n  address: addressProp,\n  chainId,\n  hideZero = true,\n  currency = \"USD\",\n  locale,\n  balances,\n  holdings,\n  isLoading: isLoadingProp = false,\n  isSpam,\n  showUnlisted,\n  hideUnpriced,\n  minValue = 0.5,\n  pageSize = 10,\n  title = \"Portfolio\",\n  className,\n}: PortfolioProps) {\n  const [visible, setVisible] = useState(pageSize);\n  const [showHidden, setShowHidden] = useState(false);\n  const [hiddenVisible, setHiddenVisible] = useState(pageSize);\n  const hiddenId = useId();\n  const { address: connected } = useConnection();\n  const address = addressProp ?? connected;\n  const { rows, hidden, total, unpriced, isLoading, isError } = usePortfolio({\n    tokens,\n    prices,\n    address,\n    chainId,\n    hideZero,\n    balances,\n    // Your own data is on its way: don't fall back to RPC reads meanwhile.\n    holdings: holdings ?? (isLoadingProp && !balances ? noHoldings : undefined),\n    isSpam,\n    showUnlisted,\n    hideUnpriced,\n    minValue,\n  });\n  const money = new Intl.NumberFormat(locale, { style: \"currency\", currency });\n  const notes: Record<HiddenReason, string> = {\n    spam: \"Likely spam\",\n    unlisted: \"Not on the token list\",\n    unpriced: \"No price\",\n    dust: `Under ${money.format(minValue)}`,\n  };\n  const phase = isLoadingProp\n    ? \"loading\"\n    : !address && !balances && !holdings\n      ? \"idle\"\n      : isLoading\n        ? \"loading\"\n        : isError\n          ? \"error\"\n          : rows.length || hidden.length\n            ? \"ready\"\n            : \"empty\";\n  // The skeleton is measured from what will be shown: the real rows when they\n  // are already known (your own data, a refetch), sample rows otherwise.\n  const known = rows.length > 0 || hidden.length > 0;\n  const listRows = phase === \"loading\" && !known ? sampleRows : rows.slice(0, visible);\n\n  return (\n    <section\n      data-slot=\"portfolio\"\n      data-phase={phase}\n      aria-label={typeof title === \"string\" ? title : \"Portfolio\"}\n      className={cn(\"flex flex-col gap-3 rounded-2xl border p-4\", className)}\n    >\n      <header className=\"flex items-baseline justify-between gap-2\">\n        {title && <h3 className=\"font-semibold\">{title}</h3>}\n        {phase === \"loading\" && (\n          <span className=\"text-2xl font-semibold\">\n            {/* About the width of \"$1,234.56\". */}\n            <SkeletonBox width=\"9ch\" height=\"1em\" style={inlineBox} />\n          </span>\n        )}\n        {phase === \"ready\" && (\n          <span className=\"text-2xl font-semibold tabular-nums\">\n            <MorphText>{money.format(total)}</MorphText>\n            {unpriced > 0 && <span className=\"sr-only\">, plus {unpriced} tokens without a price</span>}\n          </span>\n        )}\n      </header>\n\n      {phase === \"idle\" && (\n        <p className=\"py-6 text-center text-sm text-muted-foreground\">Connect a wallet to see its tokens.</p>\n      )}\n      {phase === \"error\" && (\n        <p role=\"alert\" className=\"py-6 text-center text-sm text-destructive\">\n          Couldn't load balances. Check your connection and try again.\n        </p>\n      )}\n      {phase === \"empty\" && (\n        <p className=\"py-6 text-center text-sm text-muted-foreground\">No tokens from this list in this wallet.</p>\n      )}\n\n      {/* One tree for loading and ready: while loading it is measured into a\n          skeleton, so the content arrives exactly where its skeleton was. */}\n      {(phase === \"loading\" || phase === \"ready\") && (\n        <Skeleton loading={phase === \"loading\"} label=\"Loading tokens\">\n          <div className=\"flex flex-col gap-3\">\n            {phase === \"ready\" && rows.length === 0 && (\n              <p className=\"py-4 text-center text-sm text-muted-foreground\">Every token in this wallet is hidden.</p>\n            )}\n            {listRows.length > 0 && (\n              <ul className=\"flex flex-col\">\n                {listRows.map((row) => (\n                  <Holding\n                    key={`${row.token.chainId}-${row.token.address}`}\n                    row={row}\n                    money={money}\n                    locale={locale}\n                  />\n                ))}\n              </ul>\n            )}\n            {rows.length > visible && (\n              <ShowMore remaining={rows.length - visible} onClick={() => setVisible((v) => v + pageSize)} />\n            )}\n\n            {hidden.length > 0 && (\n              <div className=\"flex flex-col border-t pt-2\">\n                <button\n                  type=\"button\"\n                  aria-expanded={showHidden}\n                  aria-controls={hiddenId}\n                  onClick={() => setShowHidden((s) => !s)}\n                  className=\"flex items-center justify-between rounded-md py-1.5 text-sm text-muted-foreground hover:text-foreground\"\n                >\n                  Hidden tokens ({hidden.length})\n                  <ChevronDownIcon\n                    aria-hidden\n                    className={cn(\"size-4 transition-transform\", showHidden && \"rotate-180\")}\n                  />\n                </button>\n                {showHidden && (\n                  <>\n                    <ul id={hiddenId} aria-label=\"Hidden tokens\" className=\"flex flex-col opacity-80\">\n                      {hidden.slice(0, hiddenVisible).map((row) => (\n                        <Holding\n                          key={`${row.token.chainId}-${row.token.address}`}\n                          row={row}\n                          money={money}\n                          locale={locale}\n                          note={notes[row.hidden!]}\n                        />\n                      ))}\n                    </ul>\n                    {hidden.length > hiddenVisible && (\n                      <ShowMore\n                        remaining={hidden.length - hiddenVisible}\n                        onClick={() => setHiddenVisible((v) => v + pageSize)}\n                      />\n                    )}\n                  </>\n                )}\n              </div>\n            )}\n          </div>\n        </Skeleton>\n      )}\n    </section>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "docs": "Docs: https://0xui.io/blocks/portfolio.md",
  "categories": [
    "blocks"
  ],
  "type": "registry:block"
}