> ## 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 without leaving the pool

# Swaps

A swap exchanges one token in your private balance for another. The server
quotes a route through an aggregator, the SDK signs that exact route into a
Gateway unshield, and the output token comes back to you as a new private
note. If the route can't deliver the signed minimum when it executes, the
input is refunded to your private balance instead.

A swap needs a signed-in session. It runs on the root SDK only: a
`sdk.forChain()` client rejects it with `UNSUPPORTED_OPERATION`.

## Checking Availability

Swaps run through the Gateway's `1inch-classic` adapter. Check that the
deployment has it and that it can quote right now:

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

const gateway = await sdk.vault.getGatewayConfig();
const adapter = gateway.adapters.find((a) => a.id === '1inch-classic');

const canSwap =
  gateway.enabled && gateway.availability.canSubmit && !!adapter && canAdapterQuote(adapter);
```

## Quoting and Swapping

Swaps address tokens by their pool token ID, not their contract address. Read
the IDs from `getRegisteredTokens()`, and use `tokenAllowsSwapOutput` to check
that a pair is routable before offering it.

Then fetch a quote, show it, and execute the quote the user confirmed with
`swapFromQuote`. The quote is passed through unchanged, so the route and
minimum the user saw are exactly what gets signed.

```typescript theme={null}
import {
  isSwapQuoteExecutable,
  swapQuoteEconomics,
  tokenAllowsSwapOutput,
} from '@sunnyside-io/privacy-boost';

const tokens = await sdk.vault.getRegisteredTokens();
const usdc = tokens.find((t) => t.symbol === 'USDC');
const weth = tokens.find((t) => t.symbol === 'WETH');
if (!usdc || !weth || !tokenAllowsSwapOutput(usdc, weth.id)) {
  throw new Error('USDC to WETH is not routable on this deployment');
}

// 1. Quote. Nothing is submitted.
const quote = await sdk.vault.createSwapQuote({
  inputTokenId: usdc.id,
  outputTokenId: weth.id,
  inputAmount: 100_000_000n, // 100 USDC (6 decimals)
  maxSlippageBps: 50,        // the default
});

// 2. Show the economics.
const economics = swapQuoteEconomics(quote, usdc, weth);
console.log('You receive about', quote.expectedOutputAmount);
console.log('At least', quote.minOutputAmount);
console.log('Rate', economics.rate, 'slippage bound', economics.slippageBps, 'bps');

// 3. Execute once the user confirms, if the quote is still fresh.
if (!isSwapQuoteExecutable(quote)) {
  throw new Error('Quote expired; fetch a new one');
}
const result = await sdk.vault.swapFromQuote({
  quote,
  onProgress: ({ message }) => console.log(message),
});
console.log('Swap request:', result.requestId, 'fee:', result.fee);
```

A quote stays executable for `SWAP_QUOTE_MAX_AGE_MS` (two minutes) from
`quote.quotedAtMs`; after that `swapFromQuote` rejects it. Use the timestamp to
show a countdown, and re-quote rather than letting the user confirm a stale
route.

`priceImpactBps` on the quote is the trade's price impact measured against the
same route. It's absent when the server didn't measure it; treat that as
unknown, not zero. `economics.oracleVarianceBps` compares the quote with a USD
price feed instead, so it also absorbs that feed's staleness; label it as a
cross-check, not as price impact.

## Fees

The Gateway fee replaces the regular unshield fee and is charged on top of
`inputAmount`, so your shielded balance has to cover both. `result.fee` reports
the fee that was charged.

## One-Shot Swaps

`swap` quotes and executes in one call, for flows where nobody reviews the
quote. For that reason it requires `minAcceptableOutputAmount`, a floor you
choose independently of the quote, and rejects any quote whose
`minOutputAmount` is below it. Leave room for slippage: a floor at the expected
output rejects every quote.

```typescript theme={null}
const result = await sdk.vault.swap({
  inputTokenId: 1,
  outputTokenId: 2,
  inputAmount: 100_000_000n,
  // The least you'll accept, in raw output-token units.
  minAcceptableOutputAmount: 25_000_000_000_000_000n,
});
```

Prefer `createSwapQuote` with `swapFromQuote` whenever a person can see the
quote.

## Tracking Settlement

A swap settles as a Gateway unshield. Read its progress with
`getUnshieldStatus(requestId)`; the `gateway` field follows the credited note:

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

if (status.gateway?.creditStatus === 'completed') {
  if (status.gateway.settlement === 'fallback') {
    // The route missed its minimum. The input token was refunded to your private balance.
  } else {
    // The output token was credited as a new private note.
  }
}
```

The swap's row in history carries the same information under `gateway`. Pass
`collapseGateway: true` to `fetchHistory` to get one row per swap instead of
one per on-chain leg.

## Error Handling

A failed quote request and a refused submission each have their own codes.
Read them with the helpers rather than matching on messages.

`GATEWAY_PAIR_DISABLED` can come from either call, so both helpers return it.
It means an operator disabled the pair, possibly after you loaded the catalog,
and asking again won't help. `getRegisteredTokens({ forceRefresh: true })`
reads the current pair policy instead of the copy the SDK cached.

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

try {
  const quote = await sdk.vault.createSwapQuote({
    inputTokenId: 1,
    outputTokenId: 2,
    inputAmount: amount,
  });
  await sdk.vault.swapFromQuote({ quote });
} catch (error) {
  const quoteCode = asGatewayQuoteErrorCode(error);
  const submitCode = asGatewaySubmitErrorCode(error);

  if (quoteCode === 'GATEWAY_PAIR_DISABLED') {
    // An operator turned the pair off. Rebuild your token picker from the
    // current catalog so it stops offering the pair.
    const tokens = await sdk.vault.getRegisteredTokens({ forceRefresh: true });
    showError('This pair is no longer available');
  } else if (quoteCode) {
    // No quote: e.g. no route, or the aggregator is rate limited.
    if (isRetryableGatewayQuoteError(quoteCode)) await retryLater();
  } else if (submitCode) {
    // The server refused the swap before storing it. Nothing was submitted
    // and your notes are untouched.
    console.log('Swap refused:', submitCode);
  } else {
    // A transport failure doesn't prove the swap was refused. Check history
    // before submitting it again.
    throw error;
  }
}
```

## Approval-Only Accounts

An [approval-only account](https://docs.privacyboost.io/sdk/concepts/authentication.md) can quote like any
other, then propose the swap with `sdk.vault.buildSwapApprovalPlan(...)`. The
plan bakes in a fresh quote, so the owner approves the route that will execute.
Once the approval is on-chain, submit it with
`sdk.vault.submitPrebuiltSwapApprovalPlan(plan)`, or let
`reconcilePendingApprovals()` submit it. See
[Approval plans](https://docs.privacyboost.io/sdk/typescript/api-reference.md#approval-plans).

## Next Steps

* [Transactions Guide](https://docs.privacyboost.io/sdk/typescript/guides/transactions.md)
* [Balances Guide](https://docs.privacyboost.io/sdk/typescript/guides/balances.md)
* [API Reference](https://docs.privacyboost.io/sdk/typescript/api-reference.md#swaps)


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