# Bridge API Documentation

## Overview

The Bridge API provides endpoints for initiating, tracking, and managing cross-chain transfers from Chain 138 to EVM chains, XRPL, and Hyperledger Fabric networks.

## Base URL

```
https://api.bridge.chain138.example.com
```

## Authentication

Most endpoints require authentication via API key:

```
Authorization: Bearer <api_key>
```

## Endpoints

### 1. Get Bridge Quote

Get a quote for bridging tokens to a destination chain.

**Endpoint:** `POST /api/bridge/quote`

**Request Body:**
```json
{
  "token": "0x0000000000000000000000000000000000000000",
  "amount": "1000000000000000000",
  "destinationChainId": 137,
  "destinationType": 0,
  "destinationAddress": "0x..."
}
```

**Response:**
```json
{
  "transferId": "0x...",
  "routes": [
    {
      "chainId": 137,
      "chainName": "Polygon",
      "provider": "thirdweb",
      "estimatedTime": 300,
      "fee": "1000000000000000",
      "healthScore": 9500
    }
  ],
  "recommendedRoute": {
    "chainId": 137,
    "chainName": "Polygon",
    "provider": "thirdweb",
    "estimatedTime": 300,
    "fee": "1000000000000000",
    "healthScore": 9500
  },
  "totalFee": "1000000000000000",
  "minReceived": "999000000000000000",
  "estimatedTime": 300,
  "slippage": "50",
  "riskLevel": 0,
  "sourceSwapQuote": "998000000000000000",
  "destinationSwapQuote": "997000000000000000"
}
```

When EnhancedSwapRouter is configured, the response may include `sourceSwapQuote` and `destinationSwapQuote` (best Dodoex-inclusive swap quote on source and destination chain).

### 1b. Swap + Bridge + Swap Quote (full path)

Get a combined quote for swapping on source chain, bridging, then swapping on destination chain.

**Endpoint:** `POST /api/bridge/quote`

**Request Body (extended for swap+bridge+swap):**
```json
{
  "sourceToken": "0x...",
  "destinationToken": "0x...",
  "sourceChainId": 138,
  "destinationChainId": 137,
  "amount": "1000000000000000000",
  "destinationAddress": "0x..."
}
```

**Response:** Same as Get Bridge Quote; `minReceived` reflects the full path when source/destination swap routers are configured. Use `sourceSwapQuote` and `destinationSwapQuote` for per-leg amounts. Initiate flow: (1) source tx: swap + bridge via SwapBridgeSwapCoordinator.swapAndBridge, (2) destination tx: claim + swap via BridgeSwapCoordinator.bridgeAndSwap or coordinator contract.

### 2. Initiate XRPL Bridge

Initiate a bridge transfer to XRPL.

**Endpoint:** `POST /api/bridge/xrpl/initiate`

**Request Body:**
```json
{
  "amount": "1000000000000000000",
  "destinationAddress": "rXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "destinationTag": 12345,
  "token": "0x0000000000000000000000000000000000000000"
}
```

**Response:**
```json
{
  "transferId": "0x...",
  "status": "INITIATED",
  "timestamp": 1234567890
}
```

### 3. Get Transfer Status

Get the current status of a bridge transfer.

**Endpoint:** `GET /api/bridge/status/:transferId`

**Response:**
```json
{
  "transferId": "0x...",
  "status": "EXECUTING",
  "depositor": "0x...",
  "asset": "0x0000000000000000000000000000000000000000",
  "amount": "1000000000000000000",
  "destinationType": 0,
  "destinationData": "0x...",
  "timestamp": 1234567890,
  "timeout": 3600,
  "refunded": false,
  "executionData": {
    "txHash": "0x...",
    "blockNumber": 12345
  },
  "route": {
    "chainId": 137,
    "chainName": "Polygon",
    "provider": "thirdweb",
    "estimatedTime": 300,
    "fee": "1000000000000000",
    "healthScore": 9500
  },
  "isRefundable": false,
  "refundDeadline": 1234567890
}
```

### 4. Get XRPL Quote

Get a quote for bridging to XRPL.

**Endpoint:** `POST /api/bridge/xrpl/quote`

**Request Body:**
```json
{
  "token": "0x0000000000000000000000000000000000000000",
  "amount": "1000000000000000000",
  "destinationAddress": "rXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "destinationTag": 12345
}
```

**Response:**
```json
{
  "fee": "2000000000000000",
  "minReceived": "998000000000000000",
  "estimatedTime": 60,
  "route": {
    "chainId": 0,
    "chainName": "XRPL",
    "provider": "cacti-xrpl",
    "estimatedTime": 60,
    "fee": "2000000000000000",
    "healthScore": 8000
  }
}
```

## Admin Endpoints

### 5. Get Bridge Metrics

Get aggregated bridge metrics.

**Endpoint:** `GET /api/admin/metrics`

**Response:**
```json
{
  "totalTransfers": 1000,
  "successRate": 98.5,
  "avgSettlementTime": 285,
  "refundRate": 1.2,
  "liquidityFailures": 5
}
```

### 6. List Transfers

List recent transfers with optional filters.

**Endpoint:** `GET /api/admin/transfers`

**Query Parameters:**
- `limit` (optional): Number of results (default: 50)
- `offset` (optional): Pagination offset (default: 0)
- `status` (optional): Filter by status
- `depositor` (optional): Filter by depositor address

**Response:**
```json
{
  "transfers": [
    {
      "transferId": "0x...",
      "status": "COMPLETED",
      "depositor": "0x...",
      "amount": "1000000000000000000",
      "destinationType": 0,
      "timestamp": 1234567890
    }
  ],
  "total": 1000,
  "limit": 50,
  "offset": 0
}
```

### 7. Pause Bridge Operations

Pause bridge operations globally or for specific token/destination.

**Endpoint:** `POST /api/admin/pause`

**Request Body:**
```json
{
  "type": "global",
  "id": null
}
```

**Types:**
- `global`: Pause all operations
- `token`: Pause specific token (provide token address in `id`)
- `destination`: Pause specific destination (provide chainId in `id`)

**Response:**
```json
{
  "success": true,
  "message": "Bridge paused successfully"
}
```

### 8. Initiate Refund

Manually initiate a refund for a failed transfer.

**Endpoint:** `POST /api/admin/refund/:transferId`

**Response:**
```json
{
  "success": true,
  "transferId": "0x...",
  "status": "REFUND_PENDING"
}
```

## Error Responses

All endpoints may return error responses in the following format:

```json
{
  "error": {
    "code": "ERROR_CODE",
    "message": "Human-readable error message",
    "details": {}
  }
}
```

### Error Codes

- `INVALID_REQUEST`: Invalid request parameters
- `TRANSFER_NOT_FOUND`: Transfer ID not found
- `INSUFFICIENT_BALANCE`: Insufficient balance for transfer
- `INVALID_ROUTE`: No valid route available
- `BRIDGE_PAUSED`: Bridge operations are currently paused
- `UNAUTHORIZED`: Authentication required
- `FORBIDDEN`: Insufficient permissions
- `INTERNAL_ERROR`: Internal server error

## Rate Limiting

API requests are rate-limited:
- **Public endpoints**: 100 requests per minute per IP
- **Admin endpoints**: 1000 requests per minute per API key

Rate limit headers are included in responses:
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1234567890
```

## WebSocket Events

Real-time transfer status updates are available via WebSocket:

**Connection:** `wss://api.bridge.chain138.example.com/ws`

**Subscribe to transfer:**
```json
{
  "action": "subscribe",
  "transferId": "0x..."
}
```

**Event:**
```json
{
  "event": "transfer_status_update",
  "transferId": "0x...",
  "status": "EXECUTING",
  "timestamp": 1234567890
}
```

## SDK Examples

### JavaScript/TypeScript

```typescript
import { BridgeClient } from '@chain138/bridge-sdk';

const client = new BridgeClient({
  apiUrl: 'https://api.bridge.chain138.example.com',
  apiKey: 'your-api-key'
});

// Get quote
const quote = await client.getQuote({
  token: '0x0000000000000000000000000000000000000000',
  amount: '1000000000000000000',
  destinationChainId: 137,
  destinationType: 0,
  destinationAddress: '0x...'
});

// Initiate transfer
const transfer = await client.initiateTransfer(quote);
```

### Python

```python
from chain138_bridge import BridgeClient

client = BridgeClient(
    api_url='https://api.bridge.chain138.example.com',
    api_key='your-api-key'
)

# Get quote
quote = client.get_quote(
    token='0x0000000000000000000000000000000000000000',
    amount='1000000000000000000',
    destination_chain_id=137,
    destination_type=0,
    destination_address='0x...'
)

# Initiate transfer
transfer = client.initiate_transfer(quote)
```

## Support

For API support, contact:
- Email: api-support@chain138.example.com
- Documentation: https://docs.bridge.chain138.example.com
- Status: https://status.bridge.chain138.example.com
