> ## 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.

# Privy

> Give users a private balance from a Privy embedded Solana wallet, with email, Google or passkey login

[Privy](https://privy.io) creates a Solana wallet for a user at login, with no extension and no seed
phrase. This guide wires a Privy embedded wallet into `createCloak`, so the same login gives the user
a private balance. External wallets connected through Privy work the same way.

Tested against `@privy-io/react-auth` 3.52.1 and `@cloak.dev/sdk` 0.2.20.

## How it works

| Step | Who signs | Prompt |
| - | - | - |
| Login | Privy | Privy's login modal |
| Open the Cloak account | The embedded wallet signs `CLOAK_ACCOUNT_MESSAGE` | Twice on first use on a device, then once |
| Shield USDC from the wallet | The embedded wallet signs one transaction | Once per shield |
| Private send, withdrawal | A key derived from the Cloak account | None |

The embedded wallet is an ordinary ed25519 key held by Privy, so it signs the account message the same
way every time. `createCloak` checks that on first use by signing twice and comparing, and refuses a
wallet whose signatures differ instead of silently opening a different account.

> [!NOTE]
>
> Privy smart wallets are not Solana wallets. Privy's smart wallets are ERC-4337 accounts on EVM
> chains. Use the embedded Solana wallet for Cloak. See [Smart wallets](https://docs.cloak.ag/wallets/smart-wallets.md).

## Prerequisites

* A Privy app with Solana embedded wallets enabled. Copy its App ID.
* A Next.js (App Router) or React app.
* A mainnet RPC URL and its WebSocket URL.

```bash theme={null}
npm install @cloak.dev/sdk@^0.2.20 @solana/kit @privy-io/react-auth @stripe/stripe-js@^1
```

`@stripe/stripe-js` is needed by a Privy module that webpack (the Next.js default bundler) resolves at
build time.

```bash .env.local theme={null}
NEXT_PUBLIC_PRIVY_APP_ID=your-privy-app-id
NEXT_PUBLIC_SOLANA_RPC_URL=https://your-mainnet-rpc
NEXT_PUBLIC_SOLANA_WS_URL=wss://your-mainnet-rpc
```

> [!WARNING]
>
> `NEXT_PUBLIC_` variables ship to the browser. Use an RPC key restricted to your domain, or proxy RPC
> through your own route. See [Network and RPC](https://docs.cloak.ag/resources/network-and-rpc.md).

## 1. Configure the Privy provider

Create Solana embedded wallets at login and give Privy a mainnet RPC. Privy's Solana wallet hooks need
the `solana.rpcs` entry.

```tsx title="app/providers.tsx" theme={null}
"use client";

import { PrivyProvider } from "@privy-io/react-auth";
import { createSolanaRpc, createSolanaRpcSubscriptions } from "@solana/kit";
import type { ReactNode } from "react";

const RPC_URL = process.env.NEXT_PUBLIC_SOLANA_RPC_URL!;
const WS_URL = process.env.NEXT_PUBLIC_SOLANA_WS_URL!;

export function Providers({ children }: { children: ReactNode }) {
  return (
    <PrivyProvider
      appId={process.env.NEXT_PUBLIC_PRIVY_APP_ID!}
      config={{
        loginMethods: ["email", "google", "passkey"],
        embeddedWallets: {
          solana: { createOnLogin: "users-without-wallets" },
        },
        solana: {
          rpcs: {
            "solana:mainnet": {
              rpc: createSolanaRpc(RPC_URL),
              rpcSubscriptions: createSolanaRpcSubscriptions(WS_URL),
            },
          },
        },
      }}
    >
      {children}
    </PrivyProvider>
  );
}
```

Wrap your root layout with `<Providers>`.

## 2. Get the embedded wallet

`useWallets()` from `@privy-io/react-auth/solana` returns `ConnectedStandardSolanaWallet` objects.
Pass one to `createCloak` as it is. The SDK recognizes it and drives the wallet's standard
`solana:signMessage` and `solana:signTransaction` features.

```ts theme={null}
import { useWallets } from "@privy-io/react-auth/solana";

function useEmbeddedWallet() {
  const { ready, wallets } = useWallets();
  // The embedded wallet reports the Wallet Standard name "Privy". External wallets
  // connected through Privy report their own name and work the same way.
  const embedded = wallets.find((w) => w.standardWallet.name === "Privy");
  return { ready, wallet: embedded };
}
```

## 3. Open the Cloak account

Keep the opened account in React state. Open it after an explicit user action, because it asks the
wallet to sign.

```ts title="hooks/use-cloak.ts" theme={null}
"use client";

import { usePrivy } from "@privy-io/react-auth";
import { useWallets } from "@privy-io/react-auth/solana";
import { createCloak, isCloakCallError, type Cloak } from "@cloak.dev/sdk";
import { useCallback, useState } from "react";

export function useCloak() {
  const { ready, authenticated } = usePrivy();
  const { ready: walletsReady, wallets } = useWallets();
  const [cloak, setCloak] = useState<Cloak | null>(null);
  const [error, setError] = useState<string | null>(null);

  const embedded = wallets.find((w) => w.standardWallet.name === "Privy");

  const open = useCallback(async () => {
    if (!ready || !authenticated || !walletsReady || !embedded) return;
    setError(null);
    try {
      const opened = await createCloak({
        wallet: embedded,
        rpc: process.env.NEXT_PUBLIC_SOLANA_RPC_URL,
        onWarning: (message) => console.warn("[cloak]", message),
      });
      setCloak(opened);
    } catch (e) {
      setError(isCloakCallError(e) ? `${e.code}: ${e.message}` : String(e));
    }
  }, [ready, authenticated, walletsReady, embedded]);

  return { cloak, open, error, wallet: embedded };
}
```

`cloak.address` is the user's `cloak_` address. The same Privy login opens the same Cloak account on
any device, because the account comes from the wallet's signature.

## 4. Shield, send and withdraw

```tsx title="components/private-balance.tsx" theme={null}
"use client";

import { isCloakCallError } from "@cloak.dev/sdk";
import { useState } from "react";
import { useCloak } from "../hooks/use-cloak";

export function PrivateBalance() {
  const { cloak, open, error } = useCloak();
  const [status, setStatus] = useState("");
  const [balance, setBalance] = useState<Record<string, string> | null>(null);

  async function run(label: string, action: () => Promise<unknown>) {
    setStatus(`${label}…`);
    try {
      await action();
      setBalance(await cloak!.balance());
      setStatus(`${label}: done`);
    } catch (e) {
      setStatus(isCloakCallError(e) ? `${e.code}: ${e.message}` : String(e));
    }
  }

  if (!cloak) return <button onClick={open}>Open private balance</button>;

  return (
    <div>
      <p>Cloak address: {cloak.address}</p>
      <p>Balance: {balance ? `${balance.USDC} USDC` : "…"}</p>
      <button
        onClick={() =>
          run("Shielding", () =>
            cloak.shield({ from: "solana", token: "USDC", amount: "5", onProgress: setStatus }),
          )
        }
      >
        Shield 5 USDC
      </button>
      <button
        onClick={() =>
          run("Sending", () => cloak.send({ to: "cloak_…", token: "USDC", amount: "1", onProgress: setStatus }))
        }
      >
        Send 1 USDC privately
      </button>
      <p>{status}</p>
      {error && <p role="alert">{error}</p>}
    </div>
  );
}
```

The shield asks the embedded wallet to sign one transaction. The wallet needs the USDC and a little
SOL for the network fee. The send and any withdrawal do not prompt the wallet at all.

## What the user sees

* **Signature prompts.** Whether Privy shows its own confirmation for each signature follows your
  `embeddedWallets.showWalletUIs` setting, or the dashboard's when unset.
* **First open.** Two signatures of the Cloak account message, then the address appears.
* **Proof time.** Each shield, send and withdrawal generates a zero-knowledge proof in the browser.
  The first one also downloads about 23 MB of circuit files. Show `onProgress` text, and warm the
  circuits on mount with `verifyAllCircuits(getCircuitsPath())`.

## Funding the embedded wallet

A new embedded wallet is empty. A shield from Solana needs the token plus a little SOL for the
network fee, paid by the wallet. Two ways around that:

* **Shield from another chain.** If the user holds USDC on Base or Polygon in an EVM wallet, pass that
  wallet too and call `shield({ from: "base", ... })`. The Solana side needs no SOL. See
  [EVM wallets](https://docs.cloak.ag/wallets/evm-wallets.md).
* **Sponsor the deposit** with the low-level API's `externalFeePayer`. See
  [Custom signers](https://docs.cloak.ag/wallets/custom-signers.md#sponsored-deposits).

Privy's own gas sponsorship only applies to transactions sent through Privy's sign-and-send call. The
SDK signs with the wallet and submits through your RPC, so that sponsorship does not cover Cloak
shields.

## Server-side Privy wallets

A Privy server wallet is a `@solana/kit` signer from `createSolanaKitSigner` in `@privy-io/node`.
`createCloak` accepts it as a wallet and ignores its ability to send. See
[Custom signers](https://docs.cloak.ag/wallets/custom-signers.md#privy-server-wallets).

## Troubleshooting

| Symptom | Cause | Fix |
| - | - | - |
| `No RPC configuration found for chain solana:mainnet` from Privy | `solana.rpcs` missing in the provider config | Add the `solana:mainnet` entry |
| `wallets` is empty after login | The user has no Solana wallet yet | Set `embeddedWallets.solana.createOnLogin`, or create one with Privy's `useCreateWallet` |
| `StoredAccountRequiredError` | The wallet did not sign the account message the same way twice | You passed a non-deterministic wallet; use the embedded Solana wallet |
| `WalletSignatureChangedError` | The wallet now signs differently than when the account was set up on this device | Do not open a new account; restore from a backup or a Cloak Key |
| `shield.failed` mentioning funds or fees | The wallet lacks the token or SOL for the fee | Fund the wallet, or shield from another chain |

## Related

* [Privy example app](https://docs.cloak.ag/examples/privy.md): the complete Next.js project.
* [createCloak](https://docs.cloak.ag/sdk/create-cloak.md): every call and receipt.
* [Wallet integrations](https://docs.cloak.ag/wallets/overview.md): how other wallet types compare.


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