> ## 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 a shielded balance into an ERC-4626 vault and redeem it without leaving the pool

# Earn

Earn puts part of a private balance into an ERC-4626 yield vault. A deposit
spends a private note of the vault's asset, the Gateway calls the vault's
`deposit`, and the vault shares come back to you as a new private note. A
redeem does the reverse: it spends share notes 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.

[Earn](https://docs.privacyboost.io/sdk/concepts/earn.md) explains how the Gateway settles these operations
and what stays private.

Depositing and redeeming need a signed-in session. Earn runs on the root SDK
only: a `sdk.forChain()` client rejects it with `UNSUPPORTED_OPERATION`.

## Checking Availability

Earn needs the external call Gateway. `getGatewayConfig()` works before
sign-in:

```typescript theme={null}
const gateway = await sdk.vault.getGatewayConfig();

if (!gateway.enabled || !gateway.availability.canSubmit) {
  console.log('Earn unavailable:', gateway.availability.reason);
}
```

`availability.retryable` says whether `canSubmit: false` is expected to clear
on its own.

## Finding Vaults

The vaults you can use are the ERC-4626 routes in the token catalog. An asset
token lists an `erc4626` capability with `direction: 'deposit'` for each vault
it can enter, and the vault's share token lists one with `direction: 'redeem'`.
The share token's address is the vault address.

```typescript theme={null}
const tokens = await sdk.vault.getRegisteredTokens();

const vaults = tokens.flatMap((asset) =>
  (asset.capabilities ?? [])
    .filter((c) => c.adapter === 'erc4626' && c.direction === 'deposit' && c.vault)
    .map((c) => ({ asset, vaultAddress: c.vault as Hex, shareTokenId: c.shareTokenId })),
);
```

Some deployments also run a vault catalog with display data: APY, TVL,
curators, warnings, and availability per operation. It's optional. A
deployment without it still supports deposits and redemptions, so treat a
failed read as "no metadata", not "no earn".

```typescript theme={null}
const catalog = await sdk.vault.listEarnVaults().catch(() => null);

for (const vault of catalog?.vaults ?? []) {
  if (!vault.listed) continue;
  console.log(vault.name, vault.asset.symbol, 'net APY', vault.apy.net);
  if (!vault.availability.deposit.canSubmit) {
    console.log('  deposits unavailable:', vault.availability.deposit.reason);
  }
  for (const warning of vault.warnings) console.log('  warning:', warning.type);
}
```

APY values are fractions (`0.05` is 5%). For TVL and APY charts, see
[Vault history charts](https://docs.privacyboost.io/sdk/concepts/earn.md#vault-history-charts).

## Depositing

`amount` is net: exactly the assets that enter the vault. The Gateway fee is
charged on top, so the asset balance has to cover `amount + fee` (see
[Fees](#fees)). `previewEarnOutput` reads the vault's `previewDeposit`
on-chain, which is what to show before the user confirms:

```typescript theme={null}
const shares = await sdk.vault.previewEarnOutput('deposit', vaultAddress, 100_000_000n);
console.log('You receive about', shares, 'shares');

const result = await sdk.vault.earnDeposit({
  vaultAddress,
  amount: 100_000_000n, // 100 USDC (6 decimals), before the fee
  maxSlippageBps: 100, // the default
  onProgress: ({ message }) => console.log(message),
});
console.log('Request', result.requestId, 'fee', result.fee);
console.log('Expected', result.expectedOutputAmount, 'at least', result.minOutputAmount);
```

The SDK reads the preview again while it builds the request and signs
`minOutputAmount`: the preview less `maxSlippageBps`. A value above the
deployment's `gateway.constraints.maxSlippageBps` is lowered to it. If the
vault would mint fewer shares than that when the request executes, the deposit
settles as a refund.

A vault can stop taking deposits while its route is still enabled, for example
once it reaches a supply cap. Read `maxDeposit` for the Gateway executor, the
address the vault mints shares to, and hide the deposit when it's below the
amount:

```typescript theme={null}
import { createPublicClient, http, parseAbi } from 'viem';
import { optimism } from 'viem/chains';

const gateway = await sdk.vault.getGatewayConfig();
// Use the pool's chain.
const publicClient = createPublicClient({ chain: optimism, transport: http() });

const capacity = await publicClient.readContract({
  address: vaultAddress,
  abi: parseAbi(['function maxDeposit(address receiver) view returns (uint256)']),
  functionName: 'maxDeposit',
  args: [gateway.executorAddress as Hex],
});
const canDeposit = capacity >= amount;
```

## Redeeming

Shares sit in your private balance like any other token, under the vault
address. `amount` is the number of shares to redeem, and the fee is charged in
shares on top of it. To redeem everything, leave room for the fee:

```typescript theme={null}
import { calculateGatewayFee } from '@sunnyside-io/privacy-boost';

const REDEEM_SELECTOR = '0xba087652'; // redeem(uint256,address,address)

const gateway = await sdk.vault.getGatewayConfig();
const executor = gateway.executorAddress as Hex;
const { shieldedBalance } = await sdk.vault.getBalance(vaultAddress);
const rates = await sdk.vault.getGatewayFees(vaultAddress, executor, REDEEM_SELECTOR);

// Slightly under the maximum when the fee is a rate.
const shares =
  shieldedBalance - calculateGatewayFee(rates, shieldedBalance, executor, REDEEM_SELECTOR);

const assets = await sdk.vault.previewEarnOutput('redeem', vaultAddress, shares);
console.log('You receive about', assets);

const result = await sdk.vault.earnRedeem({ vaultAddress, amount: shares });
```

## Fees

The Gateway fee replaces the ordinary unshield fee. It's charged in the input
token (the asset for a deposit, shares for a redeem) on top of `amount`, and
it's still charged when the vault call misses its minimum and the input is
refunded. `result.fee` reports the fee that was charged.

To show the fee before submitting, price it for the Gateway executor and the
vault function's selector:

```typescript theme={null}
import { calculateGatewayFee } from '@sunnyside-io/privacy-boost';

const DEPOSIT_SELECTOR = '0x6e553f65'; // deposit(uint256,address)

const gateway = await sdk.vault.getGatewayConfig();
const executor = gateway.executorAddress as Hex;
// tokenAddress is the vault's asset.
const rates = await sdk.vault.getGatewayFees(tokenAddress, executor, DEPOSIT_SELECTOR);
const fee = calculateGatewayFee(rates, amount, executor, DEPOSIT_SELECTOR);
```

For a redeem, pass the vault address and `0xba087652`. See
[Fees](https://docs.privacyboost.io/sdk/concepts/fees.md#gateway-fees-for-earn-and-swaps) for how the
operator sets the rate.

## Tracking Settlement

A deposit or redeem settles in two steps: the unshield, then the credit of the
output note in a later epoch. Read both with `getUnshieldStatus(requestId)` and
wait for `gateway.creditStatus`, or for a failure. The top-level `status` only
covers the first step.

```typescript theme={null}
const status = await sdk.transactions.getUnshieldStatus(requestId);
const gateway = status.gateway;

if (gateway?.creditStatus === 'completed') {
  if (gateway.settlement === 'fallback') {
    // The vault call missed its minimum. The input was refunded to your private balance.
  } else {
    // The shares, or for a redeem the assets, were credited: gateway.outputAmount.
  }
} else if (gateway?.creditStatus === 'rescued') {
  // The escrow was paid to the rescue destination. Stop waiting for private credit.
} else if (
  gateway?.settlement === 'failed_before_settlement' ||
  gateway?.settlement === 'reorged' ||
  gateway?.creditStatus === 'failed'
) {
  // The operation failed and will never reach 'completed'. Stop waiting.
}
```

A request that fails before it settles on-chain reports
`settlement: 'failed_before_settlement'`, or `'reorged'` when its settlement
was reorged out. A credit that doesn't go through reports
`creditStatus: 'failed'`.

In history, an earn operation is two rows, one per step. Pass
`collapseGateway: true` to `fetchHistory` to get one row per operation.

## Error Handling

A refused deposit or redeem has a Gateway code. Read it with
`asGatewaySubmitErrorCode` rather than matching on the message:

```typescript theme={null}
import { asGatewaySubmitErrorCode } from '@sunnyside-io/privacy-boost';

try {
  await sdk.vault.earnDeposit({ vaultAddress, amount });
} catch (error) {
  const code = asGatewaySubmitErrorCode(error);

  if (code === 'GATEWAY_RECEIPT_REUSED') {
    // This exact request was accepted before and may still settle. Check history.
  } else if (code) {
    // Refused before it was stored. Nothing was submitted, and your notes are untouched.
    showError(`Deposit refused: ${code}`);
  } else {
    // A transport failure doesn't prove the request was refused. Check history
    // before submitting it again.
    throw error;
  }
}
```

A refusal's `retryable` flag follows the server's: a paused Gateway or a failed
on-chain read clears by itself, while a minimum the vault no longer meets
doesn't. `GATEWAY_ONCHAIN_PREFLIGHT_FAILED` means the server checked the vault
call on-chain and it would revert. The error's `gatewayPreflight` carries a
fresh recheck with a `reason` and a `suggestedAction`.

Codes that come before anything is sent: `INSUFFICIENT_BALANCE` when the
balance doesn't cover `amount + fee`, and `GATEWAY_FEE_NOT_CONFIGURED` when the
app has no Gateway fee set up.

## Approval-Only Accounts

`earnDeposit` and `earnRedeem` refuse an
[approval-only account](https://docs.privacyboost.io/sdk/concepts/authentication.md) with `INVALID_INPUT`. It
proposes the operation as a plan instead:

```typescript theme={null}
const plan = await sdk.vault.buildEarnApprovalPlan({
  action: 'deposit',
  vaultAddress,
  amount: 100_000_000n,
  approvalExpiry: String(Math.floor(Date.now() / 1000) + 24 * 60 * 60),
});
```

Before the owner approves, check the package with
`verifyEarnApprovalPackage(owner, expectedAuthority, authRegistryState)`, using
the AuthRegistry state that `assertApprovalOnlyAccount` returns. Once the
owner's approval is on-chain, submit the plan with
`sdk.vault.submitPrebuiltEarnApprovalPlan(plan.privatePlan)`, or let
`reconcilePendingApprovals()` submit it. Before it submits an earn plan,
`reconcilePendingApprovals()` reads the vault's preview again. A plan whose
signed minimum no longer clears would only settle as a refund, so it's reported
as `stale` and left for the user to propose again. See
[Approval plans](https://docs.privacyboost.io/sdk/typescript/api-reference.md#approval-plans).

## Next Steps

* [Earn concepts](https://docs.privacyboost.io/sdk/concepts/earn.md)
* [Swaps Guide](https://docs.privacyboost.io/sdk/typescript/guides/swaps.md)
* [Transactions Guide](https://docs.privacyboost.io/sdk/typescript/guides/transactions.md)
* [API Reference](https://docs.privacyboost.io/sdk/typescript/api-reference.md#earn-erc-4626-vaults)


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