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

# Swaps

> Swap one shielded token for another with the useSwap hook

# Swaps

The `useSwap` hook swaps one shielded token for another without leaving the
privacy pool.

A swap is a Gateway operation. The input note is spent into a server-quoted
router call (1inch), and the output arrives as a new private note. If the route
returns less than the signed minimum, the input is refunded to your private
balance instead. The Gateway fee replaces the ordinary unshield fee and is
charged on top of the input amount, so the input notes must cover both.

## useSwap

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

const { createQuote, swapFromQuote, swap, getGatewayFees, loading, error } = useSwap();
```

| Member | Description |
| - | - |
| `createQuote(params)` | Fetch and validate a quote without submitting anything |
| `swapFromQuote({ quote, onProgress? })` | Execute a quote from `createQuote`, unchanged |
| `swap(params)` | Fetch a fresh quote and submit it in one call |
| `getGatewayFees(token, gatewayAddress, selector?)` | Gateway fee rates |
| `loading`, `error` | State of the last call |

Swaps run 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. Executing a
swap unlocks first when the session is locked, like any other write.

## Pick the Tokens

Swaps take pool token IDs, which `getRegisteredTokens()` reports along with
the decimals and USD prices the quote economics need. `tokenAllowsSwapOutput`
tells you whether a pair is routable, since a token's swap capability can be
limited to an allowlist.

```tsx theme={null}
import { useEffect, useState } from 'react';
import { usePrivacyBoost } from '@sunnyside-io/privacy-boost-react';
import { tokenAllowsSwapOutput, type RegisteredToken } from '@sunnyside-io/privacy-boost';

function useSwapTokens() {
  const sdk = usePrivacyBoost();
  const [tokens, setTokens] = useState<RegisteredToken[]>([]);

  useEffect(() => {
    sdk?.vault.getRegisteredTokens().then(setTokens).catch(() => setTokens([]));
  }, [sdk]);

  const outputsFor = (input: RegisteredToken) =>
    tokens.filter((t) => tokenAllowsSwapOutput(input, t.id));

  return { tokens, outputsFor };
}
```

## Quote, Review, Execute

Show the quote before the user confirms, then pass it back to `swapFromQuote`
exactly as `createQuote` returned it. Its `callData` and `minOutputAmount` are
what get signed, so the economics the user saw are the ones executed. Amounts in
a quote are raw-unit decimal strings.

```tsx theme={null}
import { useState } from 'react';
import { useSwap } from '@sunnyside-io/privacy-boost-react';
import {
  isSwapQuoteExecutable,
  swapQuoteEconomics,
  type RegisteredToken,
  type SwapQuote,
} from '@sunnyside-io/privacy-boost';

function SwapForm({ input, output }: { input: RegisteredToken; output: RegisteredToken }) {
  const { createQuote, swapFromQuote, loading, error } = useSwap();
  const [quote, setQuote] = useState<SwapQuote | null>(null);
  const [requestId, setRequestId] = useState<string | null>(null);

  const review = async (inputAmount: bigint) => {
    setQuote(
      await createQuote({
        inputTokenId: input.id,
        outputTokenId: output.id,
        inputAmount,
        maxSlippageBps: 50,
      }),
    );
  };

  const confirm = async () => {
    if (!quote) return;
    if (!isSwapQuoteExecutable(quote)) {
      // Older than two minutes: swapFromQuote would reject it. Quote again.
      setQuote(null);
      return;
    }
    const result = await swapFromQuote({ quote });
    setRequestId(result.requestId);
  };

  const economics = quote ? swapQuoteEconomics(quote, input, output) : null;

  return (
    <div>
      <button onClick={() => review(1_000_000n)} disabled={loading}>
        Get quote
      </button>
      {quote && economics && (
        <div>
          <p>Expected: {quote.expectedOutputAmount} (minimum {quote.minOutputAmount})</p>
          {economics.rate !== null && <p>Rate: {economics.rate.toFixed(6)}</p>}
          <p>Slippage bound: {economics.slippageBps / 100}%</p>
          {quote.priceImpactBps !== undefined && (
            <p>Price impact: {quote.priceImpactBps / 100}%</p>
          )}
          <button onClick={confirm} disabled={loading}>Swap</button>
        </div>
      )}
      {requestId && <p>Swap submitted: {requestId}</p>}
      {error && <p style={{ color: 'red' }}>{error.message}</p>}
    </div>
  );
}
```

A quote stays executable for `SWAP_QUOTE_MAX_AGE_MS` (two minutes) from
`quote.quotedAtMs`; use both to show a countdown rather than let the user
confirm a stale route. `priceImpactBps` is absent when the server did not
measure it, which means unknown, not zero. `economics.oracleVarianceBps`
compares the quote against a USD price feed and also absorbs the feed's
staleness, so don't label it price impact.

## One-Shot Swaps

`swap` fetches its own quote and submits it immediately, so nobody reviews that
quote. It therefore requires `minAcceptableOutputAmount`, the least you accept
in raw output-token units. The SDK checks it against the quote's
`minOutputAmount`, the figure the Gateway settles against, so leave room for
slippage: a floor at the expected output rejects every quote.

```tsx theme={null}
const { swap } = useSwap();

const result = await swap({
  inputTokenId: input.id,
  outputTokenId: output.id,
  inputAmount: 1_000_000n,
  maxSlippageBps: 50,
  minAcceptableOutputAmount: 990_000_000_000_000n,
});
```

Prefer `createQuote` and `swapFromQuote` whenever a person is in the loop.

## Fees

`SwapResult.fee` reports the Gateway fee charged, in raw units of the input
token. To show it before submitting, call `getGatewayFees` with the input
token's address, the Gateway executor address (`executorAddress` from
`useEarn().getGatewayConfig()`), and the quote's selector, which is the first
four bytes of its calldata (`quote.callData.slice(0, 10)`). See
[useFees](https://docs.privacyboost.io/sdk/react/api-reference.md#usefees) for turning the rates into an
amount.

## Track the Swap

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

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

function SwapStatus({ requestId }: { requestId: string }) {
  const sdk = usePrivacyBoost();
  // Swaps run 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' : 'Swap complete'}</p>;
  }
  return <p>Swapping...</p>;
}
```

The hook's `client` option picks which server to ask. Added in 1.3.0. Without
it the hook asks the provider's active client,
which is the root SDK unless you set `activeClient`.

In history, a swap is two rows (the input leaving, the output arriving) unless
you fetch with `collapseGateway: true`, which folds them into one row in
`useTransactions().gatewayOperations`. See [Transactions](https://docs.privacyboost.io/sdk/react/guides/transactions.md).

## Error Handling

A rejected quote carries a Gateway code such as `GATEWAY_QUOTE_REJECTED` or
`GATEWAY_QUOTE_UNAVAILABLE`. `asGatewayQuoteErrorCode` reads it off the error,
and `isRetryableGatewayQuoteError` says whether asking again could succeed.

`GATEWAY_PAIR_DISABLED` means an operator disabled the pair, at quote time or
when the swap was submitted. It isn't retryable. Reload the token catalog with
`usePrivacyBoost()?.vault.getRegisteredTokens({ forceRefresh: true })` so the
pair drops out of your picker.

```tsx theme={null}
import {
  asGatewayQuoteErrorCode,
  isRetryableGatewayQuoteError,
  type CreateSwapQuoteParams,
} from '@sunnyside-io/privacy-boost';
import { useSwap } from '@sunnyside-io/privacy-boost-react';

function useQuoteWithMessage() {
  const { createQuote } = useSwap();

  return async (params: CreateSwapQuoteParams) => {
    try {
      return await createQuote(params);
    } catch (err) {
      const code = asGatewayQuoteErrorCode(err);
      if (code && isRetryableGatewayQuoteError(code)) {
        throw new Error('No route right now. Try again in a moment.');
      }
      throw err;
    }
  };
}
```

An approval-only account can preview quotes but not execute them with
`swapFromQuote`; it proposes the swap with `buildSwapApprovalPlan` on the
TypeScript client instead.

## Next Steps

* [Transactions Guide](https://docs.privacyboost.io/sdk/react/guides/transactions.md)
* [Balances Guide](https://docs.privacyboost.io/sdk/react/guides/balances.md)
* [API Reference: useSwap](https://docs.privacyboost.io/sdk/react/api-reference.md#useswap)
* [Earn](https://docs.privacyboost.io/sdk/concepts/earn.md): the other Gateway operation


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