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

# Swap & Bridge

> Exchange assets across chains with a unified API

<img src="https://mintcdn.com/blockradar/FrE2zfJ4u32QicMn/images/swap.jpg?fit=max&auto=format&n=FrE2zfJ4u32QicMn&q=85&s=a3cb4d76aa3218dd5b8cf2c816d55b93" alt="Swap & Bridge" width="2880" height="1620" data-path="images/swap.jpg" />

<Note>
  In a nutshell<br />
  Blockradar's Swap API lets you exchange assets on the same chain (swap) or move assets between different chains (bridge) using a single unified endpoint.
</Note>

## Prerequisites

Before using the Swap API, ensure you have:

<Steps>
  <Step title="API Key">
    Get your API key from the [Blockradar Dashboard](https://dashboard.blockradar.co). Navigate to **Developers** to generate one.
  </Step>

  <Step title="Wallet Created">
    Create a wallet via the [Create Wallet API](/en/api-reference/wallets/create-wallet) or dashboard. You'll need the `walletId` for swap operations.
  </Step>

  <Step title="Asset IDs">
    Get the `assetId` for your source and destination assets from **Assets** in the dashboard or via the [Get Assets API](/en/api-reference/miscellaneous/get-assets).
  </Step>

  <Step title="Sufficient Balance">
    Ensure your wallet has enough balance of the source asset to cover the swap amount plus network fees.
  </Step>
</Steps>

## How It Works

Blockradar automatically determines whether your transaction is a **swap** or a **bridge** based on your asset selection:

<CardGroup cols={2}>
  <Card title="Swap" icon="repeat">
    Exchange different assets on the **same blockchain**.

    *Example: USDC → USDT on Base*
  </Card>

  <Card title="Bridge" icon="bridge">
    Move assets between **different blockchains**.

    *Example: USDC on BSC → USDC on Optimism*
  </Card>
</CardGroup>

<Tip>
  You don't need to specify whether it's a swap or bridge—the API handles this automatically based on the `fromAssetId` and `toAssetId` you provide.
</Tip>

## Supported Assets & Chains

The Swap API supports major stablecoins across Blockradar-supported chains:

| Stablecoin | Description             |
| ---------- | ----------------------- |
| USDT       | Tether USD              |
| USDC       | USD Coin                |
| DAI        | Dai Stablecoin          |
| BUSD       | Binance USD             |
| cNGN       | Naira Stablecoin        |
| EURC       | Euro Coin               |
| IDRX       | Indonesian Stablecoin   |
| JPYC       | Japanese Yen Stablecoin |

<Warning>
  Asset availability varies by chain. Always use the [Get Assets API](/en/api-reference/miscellaneous/get-assets) to fetch the current list of supported assets and their `assetId` values for your target chains.
</Warning>

<Note>
  See [Integrations](/en/essentials/integrations) for the complete list of supported networks and stablecoins.
</Note>

## Master Wallet vs Child Address

The Swap API is available at two levels:

<CardGroup cols={2}>
  <Card title="Master Wallet" icon="wallet">
    Execute swaps directly from your master wallet. Ideal for treasury operations.
  </Card>

  <Card title="Child Address" icon="address-card">
    Execute swaps from individual child addresses. Perfect for user-specific operations.
  </Card>
</CardGroup>

### Endpoints

| Operation | Master Wallet                               | Child Address                                                     |
| --------- | ------------------------------------------- | ----------------------------------------------------------------- |
| Get Quote | `POST /v1/wallets/{walletId}/swaps/quote`   | `POST /v1/wallets/{walletId}/addresses/{addressId}/swaps/quote`   |
| Execute   | `POST /v1/wallets/{walletId}/swaps/execute` | `POST /v1/wallets/{walletId}/addresses/{addressId}/swaps/execute` |

## Step 1: Get a Quote

Always fetch a quote before executing a swap to show users the expected outcome.

### Request Parameters

| Parameter          | Type   | Required | Description                                                           |
| ------------------ | ------ | -------- | --------------------------------------------------------------------- |
| `fromAssetId`      | string | Yes      | The asset ID to swap from                                             |
| `toAssetId`        | string | Yes      | The asset ID to swap to                                               |
| `amount`           | string | Yes      | The amount to swap                                                    |
| `order`            | string | No       | Quote preference: `FASTEST`, `CHEAPEST`, `RECOMMENDED`, `NO_SLIPPAGE` |
| `recipientAddress` | string | No       | External wallet address (for sending to non-Blockradar wallets)       |

### Quote Example

<CodeGroup>
  ```bash Curl theme={null}
  curl --request POST \
    --url https://api.blockradar.co/v1/wallets/{walletId}/swaps/quote \
    --header 'Content-Type: application/json' \
    --header 'x-api-key: <api-key>' \
    --data '{
      "fromAssetId": "asset_usdc_base_mainnet",
      "toAssetId": "asset_usdt_bsc_mainnet",
      "amount": "100",
      "order": "RECOMMENDED"
    }'
  ```

  ```javascript JavaScript theme={null}
  const quote = await fetch(
    `https://api.blockradar.co/v1/wallets/${walletId}/swaps/quote`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': apiKey
      },
      body: JSON.stringify({
        fromAssetId: 'asset_usdc_base_mainnet',
        toAssetId: 'asset_usdt_bsc_mainnet',
        amount: '100',
        order: 'RECOMMENDED'
      })
    }
  ).then(r => r.json());

  console.log('Quote:', quote.data);
  ```
</CodeGroup>

### Quote Response

```json theme={null}
{
  "message": "Swap quote fetched successfully",
  "statusCode": 200,
  "data": {
    "amount": "99.45",
    "minAmount": "98.95",
    "rate": "0.9945",
    "impact": "0.12",
    "slippage": "0.5",
    "networkFee": "0.002",
    "networkFeeInUSD": "0.15",
    "estimatedArrivalTime": 180
  }
}
```

### Understanding Quote Fields

| Field                  | Description                                         |
| ---------------------- | --------------------------------------------------- |
| `amount`               | Estimated amount you'll receive after the swap      |
| `minAmount`            | Minimum guaranteed amount (accounting for slippage) |
| `rate`                 | Effective exchange rate (toAmount / fromAmount)     |
| `impact`               | Price impact percentage                             |
| `slippage`             | Maximum allowed price movement percentage           |
| `networkFee`           | Gas fee in native token units                       |
| `networkFeeInUSD`      | Gas fee converted to USD                            |
| `estimatedArrivalTime` | Expected completion time in seconds                 |

<Tip>
  Always display at minimum: **amount to receive**, **estimated arrival time**, and **fees** before the user confirms the swap.
</Tip>

## Step 2: Execute the Swap

Once the user confirms the quote, execute the swap.

### Request Parameters

| Parameter          | Type   | Required | Description                                                           |
| ------------------ | ------ | -------- | --------------------------------------------------------------------- |
| `fromAssetId`      | string | Yes      | The asset ID to swap from                                             |
| `toAssetId`        | string | Yes      | The asset ID to swap to                                               |
| `amount`           | string | Yes      | The amount to swap                                                    |
| `order`            | string | No       | Quote preference: `FASTEST`, `CHEAPEST`, `RECOMMENDED`, `NO_SLIPPAGE` |
| `recipientAddress` | string | No       | External wallet address (for sending to non-Blockradar wallets)       |
| `reference`        | string | No       | Your internal tracking ID                                             |
| `metadata`         | object | No       | Custom data passed through webhooks                                   |

### Execute Example

<CodeGroup>
  ```bash Curl theme={null}
  curl --request POST \
    --url https://api.blockradar.co/v1/wallets/{walletId}/swaps/execute \
    --header 'Content-Type: application/json' \
    --header 'x-api-key: <api-key>' \
    --data '{
      "fromAssetId": "asset_usdc_base_mainnet",
      "toAssetId": "asset_usdt_bsc_mainnet",
      "amount": "100",
      "order": "RECOMMENDED",
      "reference": "swap-order-12345",
      "metadata": {
        "userId": "user_abc123",
        "orderId": "order_xyz789"
      }
    }'
  ```

  ```javascript JavaScript theme={null}
  const swap = await fetch(
    `https://api.blockradar.co/v1/wallets/${walletId}/swaps/execute`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': apiKey
      },
      body: JSON.stringify({
        fromAssetId: 'asset_usdc_base_mainnet',
        toAssetId: 'asset_usdt_bsc_mainnet',
        amount: '100',
        order: 'RECOMMENDED',
        reference: 'swap-order-12345',
        metadata: {
          userId: 'user_abc123',
          orderId: 'order_xyz789'
        }
      })
    }
  ).then(r => r.json());

  console.log('Swap initiated:', swap.data);
  ```
</CodeGroup>

### Execute Response

```json theme={null}
{
  "message": "Swap transaction created successfully",
  "statusCode": 200,
  "data": {
    "id": "swap-uuid-123",
    "type": "SWAP",
    "status": "PENDING",
    "fromAsset": {
      "symbol": "USDC",
      "amount": "100",
      "blockchain": "base"
    },
    "toAsset": {
      "symbol": "USDT",
      "amount": "99.45",
      "blockchain": "bsc"
    },
    "reference": "swap-order-12345",
    "metadata": {
      "userId": "user_abc123",
      "orderId": "order_xyz789"
    },
    "createdAt": "2024-01-15T10:30:00Z"
  }
}
```

<Warning>
  Swap operations are asynchronous. The initial response shows `PENDING` status. Listen for the `swap.success` or `swap.failed` webhook to confirm completion.
</Warning>

## Order Types

Choose the right order type based on your use case:

| Order Type    | Description                 | Best For                    |
| ------------- | --------------------------- | --------------------------- |
| `FASTEST`     | Prioritizes speed over cost | Time-sensitive transactions |
| `CHEAPEST`    | Minimizes fees              | Cost-sensitive operations   |
| `RECOMMENDED` | Balanced approach (default) | Most use cases              |
| `NO_SLIPPAGE` | Exact amount or fail        | Precise amount requirements |

## Webhook Events

Monitor swap completion through webhooks:

| Event          | Description                 |
| -------------- | --------------------------- |
| `swap.success` | Swap completed successfully |
| `swap.failed`  | Swap failed                 |

### Webhook Payload

```json theme={null}
{
  "event": "swap.success",
  "data": {
    "id": "swap-uuid-123",
    "type": "SWAP",
    "status": "SUCCESS",
    "fromAsset": {
      "symbol": "USDC",
      "amount": "100",
      "blockchain": "base",
      "hash": "0xabc..."
    },
    "toAsset": {
      "symbol": "USDT",
      "amount": "99.45",
      "blockchain": "bsc",
      "hash": "0xdef..."
    },
    "reference": "swap-order-12345",
    "metadata": {
      "userId": "user_abc123",
      "orderId": "order_xyz789"
    },
    "completedAt": "2024-01-15T10:33:00Z"
  }
}
```

## Complete Flow Example

Here's a full implementation showing the quote → confirm → execute flow:

```javascript theme={null}
async function executeSwap(walletId, fromAssetId, toAssetId, amount) {
  const apiKey = process.env.BLOCKRADAR_API_KEY;
  const baseUrl = 'https://api.blockradar.co/v1';

  // Step 1: Get quote
  const quote = await fetch(
    `${baseUrl}/wallets/${walletId}/swaps/quote`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': apiKey
      },
      body: JSON.stringify({
        fromAssetId,
        toAssetId,
        amount,
        order: 'RECOMMENDED'
      })
    }
  ).then(r => r.json());

  // Step 2: Display quote to user
  console.log(`You will receive: ${quote.data.amount}`);
  console.log(`Minimum amount: ${quote.data.minAmount}`);
  console.log(`Network fee: $${quote.data.networkFeeInUSD}`);
  console.log(`Estimated time: ${quote.data.estimatedArrivalTime}s`);

  // Step 3: Execute swap (after user confirmation)
  const swap = await fetch(
    `${baseUrl}/wallets/${walletId}/swaps/execute`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': apiKey
      },
      body: JSON.stringify({
        fromAssetId,
        toAssetId,
        amount,
        order: 'RECOMMENDED',
        reference: `swap-${Date.now()}`
      })
    }
  ).then(r => r.json());

  console.log('Swap initiated:', swap.data.id);
  console.log('Status:', swap.data.status);

  // Step 4: Listen for webhook to confirm completion
  return swap.data;
}

// Usage
executeSwap(
  'wallet-uuid',
  'asset_usdc_base_mainnet',
  'asset_usdt_bsc_mainnet',
  '100'
);
```

## Error Responses

<AccordionGroup>
  <Accordion title="Insufficient Balance">
    ```json theme={null}
    {
      "message": "Insufficient balance for swap",
      "statusCode": 400,
      "error": "INSUFFICIENT_BALANCE",
      "data": {
        "required": "100",
        "available": "50.25",
        "asset": "USDC"
      }
    }
    ```
  </Accordion>

  <Accordion title="Invalid Asset ID">
    ```json theme={null}
    {
      "message": "Asset not found",
      "statusCode": 404,
      "error": "ASSET_NOT_FOUND",
      "data": {
        "assetId": "invalid_asset_id"
      }
    }
    ```
  </Accordion>

  <Accordion title="Swap Route Not Available">
    ```json theme={null}
    {
      "message": "No swap route available for this pair",
      "statusCode": 400,
      "error": "NO_ROUTE_AVAILABLE",
      "data": {
        "fromAsset": "USDC",
        "toAsset": "CUSTOM_TOKEN"
      }
    }
    ```
  </Accordion>

  <Accordion title="Amount Too Low">
    ```json theme={null}
    {
      "message": "Amount below minimum swap threshold",
      "statusCode": 400,
      "error": "AMOUNT_TOO_LOW",
      "data": {
        "minimum": "10",
        "provided": "1"
      }
    }
    ```
  </Accordion>

  <Accordion title="Slippage Exceeded">
    ```json theme={null}
    {
      "message": "Price moved beyond slippage tolerance",
      "statusCode": 400,
      "error": "SLIPPAGE_EXCEEDED",
      "data": {
        "expectedAmount": "99.45",
        "actualAmount": "97.00",
        "slippageTolerance": "0.5%"
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## Best Practices

### User Experience

* **Always show quotes**: Display amount, fees, and estimated time before execution
* **Handle slippage**: Inform users about potential price variations
* **Show progress**: Use webhooks to update users on swap status

### Security

* **Validate amounts**: Ensure swap amounts are within acceptable ranges
* **Use references**: Track swaps with unique reference IDs
* **Monitor webhooks**: Always verify swap completion via webhooks

### Performance

* **Cache asset IDs**: Store asset IDs locally to avoid repeated lookups
* **Use appropriate order types**: Choose `FASTEST` for time-sensitive, `CHEAPEST` for cost-sensitive
* **Implement retries**: Handle transient failures with exponential backoff

## API Reference

| Endpoint                                                                  | Description                       |
| ------------------------------------------------------------------------- | --------------------------------- |
| [Master Wallet Get Quote](/en/api-reference/swap/master-wallet-get-quote) | Get swap quote from master wallet |
| [Master Wallet Execute](/en/api-reference/swap/master-wallet-execute)     | Execute swap from master wallet   |
| [Child Address Get Quote](/en/api-reference/swap/child-address-get-quote) | Get swap quote from child address |
| [Child Address Execute](/en/api-reference/swap/child-address-execute)     | Execute swap from child address   |

## Support

* **Email**: [support@blockradar.co](mailto:support@blockradar.co)
* **Documentation**: [API Reference](/en/api-reference/swap/master-wallet-get-quote)
* **Blog**: [How to Swap or Bridge Assets with Blockradar](https://www.blockradar.co/blog/how-to-swap-or-bridge-assets-with-blockradar-a-follow-along-guide)

<Note>
  The Swap API provides a unified interface for both same-chain swaps and cross-chain bridges. Start with small test amounts on testnets before moving to production.
</Note>
