> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cloak.ag/llms.txt
> Use this file to discover all available pages before exploring further.

# React (Vite)

> The private balance components in a plain React app built with Vite, including the polyfills Vite needs

The same wallet-adapter integration as the [Next.js example](https://docs.cloak.ag/examples/nextjs.md), in a React app built
with Vite. Vite does not polyfill Node built-ins, and the Solana and proving libraries need `Buffer`,
`process` and `events`, so the config adds them. Built with `vite build` against
`@cloak.dev/sdk` 0.2.20 and loaded in a browser without errors.

## Install

```bash theme={null}
npm create vite@latest cloak-react -- --template react-ts
cd cloak-react
npm install @cloak.dev/sdk@^0.2.20 @solana/kit @solana/web3.js@^1.99 \
  @solana/wallet-adapter-react @solana/wallet-adapter-react-ui @solana/wallet-adapter-base
npm install -D vite-plugin-node-polyfills
```

```bash .env theme={null}
VITE_SOLANA_RPC_URL=https://your-mainnet-rpc
```

## Vite config

```ts title="vite.config.ts" theme={null}
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { nodePolyfills } from "vite-plugin-node-polyfills";

export default defineConfig({
  plugins: [
    react(),
    // The Solana and proving libraries expect Node's Buffer, process and events in the browser.
    nodePolyfills({ include: ["buffer", "process", "events", "assert"], globals: { Buffer: true, process: true } }),
  ],
});
```

> [!WARNING]
>
> Without the polyfills the app builds but renders a blank page with `ReferenceError: Buffer is not
>   defined` in the console.

## Providers and entry point

```tsx nocheck title="src/providers.tsx" theme={null}

import { ConnectionProvider, WalletProvider } from "@solana/wallet-adapter-react";
import { WalletModalProvider } from "@solana/wallet-adapter-react-ui";
import "@solana/wallet-adapter-react-ui/styles.css";
import type { ReactNode } from "react";

const RPC_URL = import.meta.env.VITE_SOLANA_RPC_URL ?? "https://api.mainnet-beta.solana.com";

export function Providers({ children }: { children: ReactNode }) {
  // An empty list: Phantom, Solflare, Backpack and every Wallet Standard wallet register themselves.
  return (
    <ConnectionProvider endpoint={RPC_URL}>
      <WalletProvider wallets={[]} autoConnect>
        <WalletModalProvider>{children}</WalletModalProvider>
      </WalletProvider>
    </ConnectionProvider>
  );
}
```

```tsx title="src/main.tsx" theme={null}
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { Providers } from "./providers";
import { PrivateBalance } from "./components/private-balance";

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <Providers>
      <PrivateBalance />
    </Providers>
  </StrictMode>,
);
```

## The hook and the component

```ts nocheck title="src/hooks/use-cloak.ts" theme={null}

import { useWallet } from "@solana/wallet-adapter-react";
import { createCloak, getCircuitsPath, isCloakCallError, verifyAllCircuits, type Cloak } from "@cloak.dev/sdk";
import { useCallback, useEffect, useState } from "react";

export function useCloak() {
  const wallet = useWallet();
  const [cloak, setCloak] = useState<Cloak | null>(null);
  const [opening, setOpening] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Start the ~23 MB circuit download now, not on the first click.
  useEffect(() => {
    void verifyAllCircuits(getCircuitsPath()).catch(() => undefined);
  }, []);

  // A different wallet is a different account.
  useEffect(() => {
    setCloak(null);
  }, [wallet.publicKey]);

  const open = useCallback(async () => {
    if (!wallet.connected) return;
    setOpening(true);
    setError(null);
    try {
      setCloak(await createCloak({ wallet, rpc: import.meta.env.VITE_SOLANA_RPC_URL }));
    } catch (e) {
      setError(isCloakCallError(e) ? `${e.code}: ${e.message}` : String(e));
    } finally {
      setOpening(false);
    }
  }, [wallet]);

  return { cloak, open, opening, error, connected: wallet.connected };
}
```

```tsx title="src/components/private-balance.tsx" theme={null}

import { isCloakCallError, type CloakReceipt } from "@cloak.dev/sdk";
import { WalletMultiButton } from "@solana/wallet-adapter-react-ui";
import { useEffect, useState } from "react";
import { useCloak } from "../hooks/use-cloak";

export function PrivateBalance() {
  const { cloak, open, opening, error, connected } = useCloak();
  const [balance, setBalance] = useState<Record<string, string> | null>(null);
  const [status, setStatus] = useState("");
  const [busy, setBusy] = useState(false);
  const [to, setTo] = useState("");
  const [amount, setAmount] = useState("1");

  useEffect(() => {
    if (cloak) void cloak.balance().then(setBalance);
  }, [cloak]);

  async function run(action: () => Promise<CloakReceipt>) {
    if (!cloak) return;
    setBusy(true);
    try {
      const receipt = await action();
      setStatus(`${receipt.status}: ${receipt.amount} ${receipt.token} (fee ${receipt.fee})`);
      setBalance(await cloak.balance());
    } catch (e) {
      setStatus(isCloakCallError(e) ? `${e.code}: ${e.message}` : String(e));
    } finally {
      setBusy(false);
    }
  }

  return (
    <section style={{ display: "grid", gap: 12, maxWidth: 480 }}>
      <WalletMultiButton />
      {connected && !cloak && (
        <button onClick={open} disabled={opening}>
          {opening ? "Check your wallet…" : "Open private balance"}
        </button>
      )}
      {error && <p role="alert">{error}</p>}
      {cloak && (
        <>
          <p>
            Your Cloak address: <code>{cloak.address}</code>
          </p>
          <p>Private USDC: {balance?.USDC ?? "…"}</p>
          <input value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="Amount (USDC)" />
          <button disabled={busy} onClick={() => run(() => cloak.shield({ from: "solana", token: "USDC", amount, onProgress: setStatus }))}>
            Shield {amount} USDC
          </button>
          <input value={to} onChange={(e) => setTo(e.target.value)} placeholder="cloak_… or a Solana address" />
          <button disabled={busy || !to} onClick={() => run(() => cloak.send({ to, token: "USDC", amount, onProgress: setStatus }))}>
            Send {amount} USDC
          </button>
          <p aria-live="polite">{status}</p>
        </>
      )}
    </section>
  );
}
```

## Run it

```bash theme={null}
npm run dev
```

The behaviour and expected output are the same as in the [Next.js example](https://docs.cloak.ag/examples/nextjs.md#5-run-it).

## Related

* [Phantom and Wallet Standard](https://docs.cloak.ag/wallets/phantom-and-wallet-standard.md)
* [Events and callbacks](https://docs.cloak.ag/reference/events-and-callbacks.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.