# Swap Engine Specification

## Overview

This document specifies the swap engine that integrates with DEX aggregators to provide optimal swap routing and execution.

## DEX Aggregator Integration

### Supported Aggregators

**1inch**: 1inch API
**0x**: 0x API
**Paraswap**: Paraswap API
**Others**: Additional aggregators as needed

### Integration Pattern

**Abstraction Layer**:
- Unified interface for all aggregators
- Quote comparison
- Best route selection

## Quote Comparison

### Quote Structure

```json
{
  "from_token": "0x...",
  "to_token": "0x...",
  "amount_in": "1000000000000000000",
  "amount_out": "2000000000000000000",
  "routes": [
    {
      "protocol": "Uniswap V3",
      "portion": 0.6
    },
    {
      "protocol": "Curve",
      "portion": 0.4
    }
  ],
  "gas_estimate": 150000,
  "slippage": 0.005,
  "price_impact": 0.01
}
```

### Comparison Algorithm

**Factors**:
1. **Output Amount**: Higher is better
2. **Gas Cost**: Lower is better
3. **Slippage**: Lower is better
4. **Price Impact**: Lower is better
5. **Execution Time**: Faster is better

**Scoring**:
```
score = (output_amount * 0.5) - (gas_cost * 0.2) - (slippage * 0.2) - (price_impact * 0.1)
```

## Routing Optimization

### Multi-Path Routing

**Strategy**: Split trade across multiple DEXs for better rates

**Implementation**:
- Get quotes from multiple aggregators
- Compare split vs single-path routes
- Select optimal route

### Slippage Calculation

**Formula**: `(expected_output - actual_output) / expected_output`

**Protection**:
- User-specified slippage tolerance
- Default: 0.5% (0.005)
- Warn if slippage high

## Approval Management

### Token Approvals

**Process**:
1. Check current allowance
2. Request approval if needed
3. Wait for approval confirmation
4. Execute swap

### Approval Optimization

**Strategies**:
- Approve max amount (one-time approval)
- Approve exact amount (safer, more transactions)
- Use permit2 (EIP-2612) if supported

### Approval Revocation

**Feature**: Allow users to revoke approvals
**UI**: Show all active approvals
**Action**: Revoke individual or all approvals

## Transaction Simulation

### Pre-Flight Simulation

**Purpose**: Verify transaction will succeed before signing

**Checks**:
- Sufficient balance
- Sufficient allowance
- Valid route
- Price impact within limits
- Gas estimation

### Simulation Result

```json
{
  "success": true,
  "simulated_output": "2000000000000000000",
  "gas_estimate": 150000,
  "warnings": [],
  "errors": []
}
```

## Execution

### Transaction Building

**Steps**:
1. Get best quote
2. Build transaction with aggregator
3. Simulate transaction
4. Present to user for approval
5. Sign and broadcast
6. Monitor confirmation

### Error Handling

**Errors**:
- Insufficient balance
- Insufficient allowance
- Slippage exceeded
- Route failure

**Recovery**:
- Retry with adjusted parameters
- Suggest alternative routes
- Provide error explanations

## API Endpoints

### Get Quote

`GET /api/v1/swap/quote`

**Parameters**:
- `from_token`: Source token address
- `to_token`: Destination token address
- `amount_in`: Input amount
- `slippage`: Slippage tolerance (optional)

**Response**: Best quote with route details

### Execute Swap

`POST /api/v1/swap/execute`

**Body**: Transaction parameters
**Response**: Transaction hash

## References

- Wallet Connectivity: See `wallet-connectivity.md`
- Safety Controls: See `safety-controls.md`

