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

# Spot Trading

> AI-optimized token swaps on Uniswap V3 and Camelot

Spot trading lets you swap tokens on Arbitrum through natural language. The agent selects the best DEX, fetches a quote, applies slippage protection, and executes the swap -- all from a single prompt.

## Supported DEXs

<CardGroup cols={2}>
  <Card title="Uniswap V3" icon="arrows-rotate">
    Concentrated liquidity with four fee tiers. Uses the UniversalRouter for optimal gas efficiency. Best for major pairs like ETH/USDC and WBTC/ETH.
  </Card>

  <Card title="Camelot" icon="shield-halved">
    Arbitrum-native V2-style AMM with volatile and stable pool types. Best for ARB ecosystem tokens, newer pairs, and long-tail assets.
  </Card>
</CardGroup>

## How It Works

The agent follows a **quote-then-execute** flow to ensure you always see expected output before committing funds.

### Step 1: Quote

When you request a swap, the agent fetches off-chain quotes from both DEXs. Quoting is a read-only operation with zero gas cost.

* **Uniswap V3** -- calls `QuoterV2.quoteExactInputSingle()` to simulate the swap through the pool and return the expected `amountOut` plus price impact.
* **Camelot** -- calls `CamelotRouter.getAmountsOut()` to calculate the output along the swap path.

The agent compares both quotes and selects the route with the best output after fees.

### Step 2: Approve

If the router does not already have sufficient token allowance, the agent sends an ERC-20 `approve` transaction before the swap.

### Step 3: Execute

The swap transaction is submitted with a computed `minAmountOut` based on your slippage tolerance. The transaction reverts on-chain if the output falls below this threshold.

## Uniswap V3 Fee Tiers

The `UniswapV3Adapter` automatically selects the 0.30% fee tier by default. You can request a specific tier in your prompt.

| Fee Tier | Rate  | Best For                      |
| -------- | ----- | ----------------------------- |
| LOWEST   | 0.01% | Stable-to-stable (USDC/USDT)  |
| LOW      | 0.05% | Stable/major pairs            |
| MEDIUM   | 0.30% | Most trading pairs            |
| HIGH     | 1.00% | Exotic or low-liquidity pairs |

## Slippage Protection

Every swap includes configurable slippage protection.

* **Default**: 0.50% (50 basis points)
* **Custom**: specify in your prompt, e.g. "swap with 0.1% slippage"

The `minAmountOut` is calculated as:

```
minAmountOut = quoteAmountOut * (10000 - slippageBps) / 10000
```

If the on-chain execution price deviates beyond your tolerance, the transaction reverts and no funds leave your wallet.

<Warning>
  High slippage tolerance on large trades can result in significant value loss from MEV sandwich attacks. Use the tightest slippage you can tolerate, or combine with [TimeBoost](/docs/features/timeboost) for priority sequencing.
</Warning>

## Price Impact Estimation

For Uniswap V3 swaps, the adapter estimates price impact by comparing the pool's `sqrtPriceX96` before and after the simulated swap. This uses fixed-point arithmetic to avoid floating-point precision issues:

```
priceRatio = (sqrtPriceAfter / sqrtPriceBefore)^2
impactBps  = |1 - priceRatio| * 10000
```

<Info>
  Price impact above 100 bps (1%) triggers a warning in the agent response. Trades above 500 bps require explicit confirmation.
</Info>

## Route Optimizer Contract

For high-value swaps, the agent can query the **RouteOptimizer** Stylus contract deployed on Arbitrum. Written in Rust, it provides 10-100x gas savings over equivalent Solidity for multi-path computation.

The RouteOptimizer maintains a dynamic registry of DEX quoters:

* **Indexed mappings** with a counter (`dex_count`) for enumeration
* **Soft-delete** via an `active` flag so DEXs can be removed without reindexing
* **Two dispatch types**: `UniV3` (concentrated liquidity quoter) and `AmmV2` (standard getAmountsOut)

The contract compares quotes across all registered DEXs for a given token pair and amount, returning the best route with the lowest price impact.

<Tip>
  The RouteOptimizer is most valuable for trades above \$10,000 where the difference between DEX quotes can save meaningful amounts.
</Tip>

## Example Prompts

Try these natural language commands with the agent:

```
Swap 100 USDC for ETH
```

```
Buy 0.5 ETH with USDC on Uniswap with 0.1% slippage
```

```
Swap 500 ARB to USDC on Camelot
```

```
What's the best price for swapping 10,000 USDC to WBTC?
```

```
Compare Uniswap and Camelot quotes for 1 ETH to USDC
```

## SDK Reference

The trading adapters are in the `@arb-agent/adapters` package:

<CardGroup cols={2}>
  <Card title="UniswapV3Adapter">
    `quote(params)` -- fetch off-chain quote via QuoterV2

    `swap(params)` -- execute via UniversalRouter
  </Card>

  <Card title="CamelotAdapter">
    `quote(params)` -- fetch off-chain quote via getAmountsOut

    `swap(params)` -- execute via CamelotRouter with referrer support
  </Card>
</CardGroup>

Both adapters accept `SwapParams` with these fields:

| Field         | Type      | Required | Description                              |
| ------------- | --------- | -------- | ---------------------------------------- |
| `tokenIn`     | `Address` | Yes      | Token to sell                            |
| `tokenOut`    | `Address` | Yes      | Token to buy                             |
| `amountIn`    | `bigint`  | Yes      | Amount of tokenIn (in token decimals)    |
| `slippageBps` | `number`  | No       | Slippage tolerance (default: 50)         |
| `deadline`    | `bigint`  | No       | Unix timestamp deadline (default: 5 min) |
| `recipient`   | `Address` | No       | Receiver address (default: sender)       |

<Note>
  The Uniswap adapter also accepts a `feeTier` parameter to override automatic fee tier selection. Valid values are `100`, `500`, `3000`, and `10000`.
</Note>
