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

# Earn

> Deposit into ERC-4626 vaults and redeem with the useEarn hook

# Earn

The `useEarn` hook moves part of a private balance into an ERC-4626 yield
vault and back without leaving the privacy pool.

A deposit spends a private note of the vault's asset and credits the vault
shares as a new private note. A redeem spends shares and credits the asset. If
the vault call can't deliver the signed minimum when it executes, the input is
refunded to your private balance instead. The Gateway fee replaces the
ordinary unshield fee and is charged on top of the amount, in the input token.
[Earn](https://docs.privacyboost.io/sdk/concepts/earn.md) explains how these operations settle.

## useEarn

```tsx theme={null}
import { useEarn } from '@sunnyside-io/privacy-boost-react';

const { vaults, deposit, redeem, previewOutput, getGatewayConfig, loading, error } = useEarn();
```

| Member | Description |
| - | - |
| `vaults` | The vault catalog, loaded as soon as the SDK is ready. `null` until the first read settles |
| `refresh()` | Reload `vaults` |
| `deposit(params)` / `redeem(params)` | Run `vault.earnDeposit` / `vault.earnRedeem` |
| `previewOutput(action, vaultAddress, amount)` | On-chain preview of the shares a deposit mints, or the assets a redeem pays |
| `getGatewayConfig()` | Gateway availability, constraints, and executor address |
| `getVault(vaultAddress)` | One vault with its owner, guardian, and share price |
| `vaultHistory(...)`, `vaultCharts(...)` | TVL and APY chart series; see [Vault history charts](https://docs.privacyboost.io/sdk/concepts/earn.md#vault-history-charts) |
| `loading`, `error` | State of the last refresh or call |

Earn runs in the key vault bound to the root SDK's chain, so the hook always
uses the root client, whatever the provider's `activeClient` is. A deposit or
redeem unlocks first when the session is locked, like any other write.

## Pick a Vault

The catalog carries what a vault picker shows: name, asset, APY, and whether
each operation is available right now. APY values are fractions (`0.05` is
5%).

```tsx theme={null}
import { useEarn } from '@sunnyside-io/privacy-boost-react';

function VaultList({ onPick }: { onPick: (vaultAddress: string) => void }) {
  const { vaults } = useEarn();
  if (!vaults) return <p>Loading vaults...</p>;

  return (
    <ul>
      {vaults.vaults
        .filter((v) => v.listed)
        .map((v) => (
          <li key={v.vaultAddress}>
            {v.name} ({v.asset.symbol})
            {v.apy.net !== undefined && <span> {(v.apy.net * 100).toFixed(2)}% APY</span>}
            <button
              onClick={() => onPick(v.vaultAddress)}
              disabled={!v.availability.deposit.canSubmit}
            >
              Deposit
            </button>
          </li>
        ))}
    </ul>
  );
}
```

The catalog is optional for a deployment. Without it, `vaults` stays `null`
and `error` holds the failed read, but deposits and redemptions still work.
Build the vault list from the ERC-4626 capabilities in `getRegisteredTokens()`
instead; see [Finding Vaults](https://docs.privacyboost.io/sdk/typescript/guides/earn.md#finding-vaults).

## Deposit

`amount` is net: exactly the assets that enter the vault. The asset balance
has to cover `amount` plus the fee. Show the preview before the user confirms:

```tsx theme={null}
import { useState } from 'react';
import { useEarn } from '@sunnyside-io/privacy-boost-react';
import type { Hex } from '@sunnyside-io/privacy-boost';

function DepositForm({ vaultAddress }: { vaultAddress: Hex }) {
  const { previewOutput, deposit, loading, error } = useEarn();
  const [shares, setShares] = useState<bigint | null>(null);
  const [requestId, setRequestId] = useState<string | null>(null);
  const amount = 100_000_000n; // 100 USDC (6 decimals), before the fee

  const review = async () => {
    setShares(await previewOutput('deposit', vaultAddress, amount));
  };

  const confirm = async () => {
    const result = await deposit({ vaultAddress, amount, maxSlippageBps: 100 });
    setRequestId(result.requestId);
  };

  return (
    <div>
      <button onClick={review} disabled={loading}>
        Preview
      </button>
      {shares !== null && (
        <div>
          <p>You receive about {shares.toString()} shares</p>
          <button onClick={confirm} disabled={loading}>
            Deposit
          </button>
        </div>
      )}
      {requestId && <p>Deposit submitted: {requestId}</p>}
      {error && <p style={{ color: 'red' }}>{error.message}</p>}
    </div>
  );
}
```

The SDK signs a minimum of the preview less `maxSlippageBps` (default 100, or
1%), capped at the deployment's limit. A vault can also stop taking deposits
while its route is enabled, for example at a supply cap. The TypeScript guide
shows how to [check its capacity](https://docs.privacyboost.io/sdk/typescript/guides/earn.md#depositing).

## Redeem

Shares sit in the private balance under the vault address. `amount` is the
number of shares to redeem, and the fee is charged in shares on top of it, so
redeeming the whole balance needs room for the fee. See
[Redeeming](https://docs.privacyboost.io/sdk/typescript/guides/earn.md#redeeming) for the calculation.

```tsx theme={null}
import { useEarn } from '@sunnyside-io/privacy-boost-react';
import type { Hex } from '@sunnyside-io/privacy-boost';

function RedeemButton({ vaultAddress, shares }: { vaultAddress: Hex; shares: bigint }) {
  const { redeem, loading } = useEarn();

  return (
    <button onClick={() => redeem({ vaultAddress, amount: shares })} disabled={loading}>
      Withdraw
    </button>
  );
}
```

## Fees

`EarnResult.fee` reports the Gateway fee charged, in raw units of the input
token. To show it before submitting, call `getGatewayFees` on `sdk.vault` (or
from `useSwap()`) with the input token's address, the `executorAddress` from
`getGatewayConfig()`, and the vault function's selector: `0x6e553f65` for a
deposit, `0xba087652` for a redeem. See
[useFees](https://docs.privacyboost.io/sdk/react/api-reference.md#usefees) for turning the rates into an
amount.

## Track the Operation

A deposit or redeem settles as an unshield followed by a credit. Follow its
`requestId` with `useUnshieldStatus`: `data.gateway.creditStatus` reaches
`'completed'` once the output note exists, and `data.gateway.settlement` says
whether the vault call executed (`'executed'`) or the input was refunded
(`'fallback'`).

```tsx theme={null}
import { usePrivacyBoost, useUnshieldStatus } from '@sunnyside-io/privacy-boost-react';

function EarnStatus({ requestId }: { requestId: string }) {
  const sdk = usePrivacyBoost();
  // Earn runs on the root SDK, so ask its server even while a chain client is active.
  const { data } = useUnshieldStatus(requestId, { client: sdk, pollInterval: 3000 });
  const gateway = data?.gateway;

  if (gateway?.creditStatus === 'completed') {
    return <p>{gateway.settlement === 'fallback' ? 'Refunded' : 'Done'}</p>;
  }
  if (gateway?.creditStatus === 'rescued') {
    return <p>Paid to the rescue address</p>;
  }
  if (
    gateway?.settlement === 'failed_before_settlement' ||
    gateway?.settlement === 'reorged' ||
    gateway?.creditStatus === 'failed'
  ) {
    return <p>Failed</p>;
  }
  return <p>Processing...</p>;
}
```

`creditStatus: 'rescued'` is final too: the escrow went to the rescue
destination, so stop waiting for private credit. So is a failure, which never
reaches `'completed'`: `settlement` is `'failed_before_settlement'` when the
request failed before it settled on-chain, `'reorged'` when its settlement was
reorged out, and `creditStatus` is `'failed'` when the credit didn't go
through.

In history, an earn operation is two rows unless you fetch with
`collapseGateway: true`, which folds them into one row in
`useTransactions().gatewayOperations`.

## Error Handling

A refused deposit or redeem carries a Gateway code. `asGatewaySubmitErrorCode`
reads it off the error. A refusal means nothing was submitted and the notes are
untouched, except `GATEWAY_RECEIPT_REUSED`: that exact request was accepted
before and may still settle.

```tsx theme={null}
import { asGatewaySubmitErrorCode, type EarnParams } from '@sunnyside-io/privacy-boost';
import { useEarn } from '@sunnyside-io/privacy-boost-react';

function useDepositWithMessage() {
  const { deposit } = useEarn();

  return async (params: EarnParams) => {
    try {
      return await deposit(params);
    } catch (err) {
      const code = asGatewaySubmitErrorCode(err);
      if (code && code !== 'GATEWAY_RECEIPT_REUSED') {
        throw new Error(`The deposit was refused (${code}). Nothing was sent.`);
      }
      throw err;
    }
  };
}
```

An error without a Gateway code, such as a dropped connection, doesn't prove
the deposit was refused. Check history before trying again. See
[Error Handling](https://docs.privacyboost.io/sdk/typescript/guides/earn.md#error-handling) in the TypeScript
guide for the codes.

## Approval-Only Accounts

`deposit` and `redeem` refuse an approval-only account with `INVALID_INPUT`.
It proposes the operation with `buildEarnApprovalPlan` on the TypeScript client
(`usePrivacyBoost()?.vault`) instead; see
[Approval-Only Accounts](https://docs.privacyboost.io/sdk/typescript/guides/earn.md#approval-only-accounts).

## Next Steps

* [Swaps](https://docs.privacyboost.io/sdk/react/guides/swaps.md)
* [Transactions](https://docs.privacyboost.io/sdk/react/guides/transactions.md)
* [API Reference](https://docs.privacyboost.io/sdk/react/api-reference.md#useearn)


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