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

# Swap

> Currency conversion (swap) enables merchants to exchange currencies directly using balances in their payment accounts. This capability is essential for multi-currency operations and balance management.

## Overview

The swap service supports the following scenarios:

* **Post-collection conversion**: Convert received payments to settlement currency
* **Unified settlement currency**: Maintain accounts in a single currency
* **Balance rebalancing**: Optimize currency distribution across accounts

For request headers, signature rules, and callback verification, refer to [Authentication & Security](/essentials/version/100/en/authenticationSecurity).

## Integration Flow

The standard swap workflow follows these steps:

```
Query tradable scope → Get quote → Create swap order → Query result
```

Each step is described in detail below.

### Step 1: Query Tradable Currency Scope (Optional)

**Endpoint:** `GET /v1/pay/convert/currency`

Retrieves the list of currencies available for conversion. This step is optional but recommended for user interface initialization and validation.

#### Query Parameters

| Parameter | Type   | Required | Description                         |
| --------- | ------ | -------- | ----------------------------------- |
| `side`    | string | No       | Filter by `buy` or `sell` direction |

#### Response Fields

The response includes available currencies with precision and amount constraints:

* `minBuyAmount`: Minimum buy amount (field precision rules apply)
* `maxBuyAmount`: Maximum buy amount (field precision rules apply)
* `minSellAmount`: Minimum sell amount (field precision rules apply)
* `maxSellAmount`: Maximum sell amount (field precision rules apply)

***

### Step 2: Query Available Currency Pairs (Optional)

**Endpoint:** `GET /v1/pay/convert/pair`

Retrieves supported trading pairs and exchange rate information.

#### Query Parameters

| Parameter  | Type   | Required | Description                         |
| ---------- | ------ | -------- | ----------------------------------- |
| `currency` | string | No       | Filter pairs by base currency       |
| `side`     | string | No       | Filter by `buy` or `sell` direction |

***

### Step 3: Get Quote

**Endpoint:** `POST /v1/pay/convert/preview`

Generates a quote for currency conversion. The quote includes an expiration timestamp; expired quotes cannot be used for order creation.

#### Request Parameters

| Field          | Type   | Required    | Description                                          |
| -------------- | ------ | ----------- | ---------------------------------------------------- |
| `buyCurrency`  | string | Yes         | Target currency to buy                               |
| `sellCurrency` | string | Yes         | Source currency to sell                              |
| `buyAmount`    | string | Conditional | Amount to buy (mutually exclusive with `sellAmount`) |
| `sellAmount`   | string | Conditional | Amount to sell (mutually exclusive with `buyAmount`) |

**Note:** Provide either `buyAmount` or `sellAmount`, but not both.

#### Response Fields

| Field            | Type      | Description                                          |
| ---------------- | --------- | ---------------------------------------------------- |
| `quoteId`        | string    | Unique quote identifier; required for order creation |
| `exchangeRate`   | string    | Current exchange rate                                |
| `buyAmount`      | string    | Amount in target currency                            |
| `sellAmount`     | string    | Amount in source currency                            |
| `expirationTime` | timestamp | Quote expiration timestamp                           |

***

### Step 4: Create Swap Order

**Endpoint:** `POST /v1/pay/convert`

Creates a currency conversion order using a valid quote. This endpoint is idempotent: submitting the same `clientReqId` multiple times will return the same business result.

#### Request Parameters

| Field          | Type   | Required | Description                                          |
| -------------- | ------ | -------- | ---------------------------------------------------- |
| `quoteId`      | string | Yes      | Quote ID from Step 3                                 |
| `buyCurrency`  | string | Yes      | Target currency                                      |
| `sellCurrency` | string | Yes      | Source currency                                      |
| `buyAmount`    | string | Yes      | Amount to buy                                        |
| `sellAmount`   | string | Yes      | Amount to sell                                       |
| `clientReqId`  | string | Yes      | Merchant-generated unique request ID for idempotency |

#### Response Fields

| Field         | Type   | Description                                   |
| ------------- | ------ | --------------------------------------------- |
| `orderId`     | string | Platform order number for queries             |
| `clientReqId` | string | Echoed from request                           |
| `status`      | string | Initial order status (typically `processing`) |
| `buyAmount`   | string | Final buy amount                              |
| `sellAmount`  | string | Final sell amount                             |

#### Example Request

```json  theme={null}
{
  "quoteId": "QUOTE_abc123",
  "buyCurrency": "BTC",
  "sellCurrency": "USDT",
  "buyAmount": "0.5",
  "sellAmount": "21500",
  "clientReqId": "SWAP_20240101_001"
}
```

***

### Step 5: Query Swap Order

**Endpoint:** `GET /v1/pay/convert/order`

Queries the status and details of a swap order. Supports multiple query keys for flexibility.

#### Query Parameters

| Parameter     | Type   | Required    | Description                   |
| ------------- | ------ | ----------- | ----------------------------- |
| `orderId`     | string | Conditional | Platform order number         |
| `clientReqId` | string | Conditional | Merchant-generated request ID |

**Note:** Provide either `orderId` or `clientReqId` (not both required, but at least one).

#### Response Fields

| Field            | Type      | Description                          |
| ---------------- | --------- | ------------------------------------ |
| `orderId`        | string    | Platform order number                |
| `clientReqId`    | string    | Merchant request ID                  |
| `status`         | string    | Order status (see enumeration below) |
| `buyCurrency`    | string    | Target currency                      |
| `sellCurrency`   | string    | Source currency                      |
| `buyAmount`      | string    | Final buy amount                     |
| `sellAmount`     | string    | Final sell amount                    |
| `completionTime` | timestamp | Order completion timestamp           |

***

## Swap Order Status Enumeration

| Status       | Description                                                     |
| ------------ | --------------------------------------------------------------- |
| `processing` | Order is being processed; check back later                      |
| `success`    | Conversion completed successfully; funds are now in the account |
| `failure`    | Conversion failed; funds returned to original account           |

## Retry and Error Handling

### Handling Uncertain Responses

If a network timeout or uncertain response occurs:

1. **Query first**: Use `GET /v1/pay/convert/order` with `clientReqId` or `orderId` to determine final status
2. **Only retry if necessary**: Only reuse the same `clientReqId` for order creation if the query result remains uncertain
3. **Preserve idempotency**: Keep `clientReqId` unchanged to ensure the same business result

### Common Failure Scenarios

| Failure Reason             | Description                                         | Resolution                                                |
| -------------------------- | --------------------------------------------------- | --------------------------------------------------------- |
| Insufficient balance       | Account does not have enough funds in sell currency | Fund the account or reduce sell amount                    |
| Unsupported trading pair   | Currency pair is not available                      | Use a different currency pair                             |
| Expired quote              | Quote lifetime has elapsed                          | Generate a new quote using `POST /v1/pay/convert/preview` |
| Invalid quantity precision | Amount does not match currency precision rules      | Adjust amount to match precision requirements             |
| Amount limit exceeded      | Amount exceeds currency limits                      | Review limits via `GET /v1/pay/convert/currency`          |

## Callback Behavior

The swap capability does not provide asynchronous callbacks. Final order confirmation must be obtained through the query API (`GET /v1/pay/convert/order`).

For information on callbacks for other products, see [Notification & Callbacks](/essentials/version/100/en/notificationCallback).

## Institution API Integration

For institutional use cases, swap endpoints are available under the institution namespace:

| Capability        | Standard Endpoint           | Institution Endpoint                                  |
| ----------------- | --------------------------- | ----------------------------------------------------- |
| Create swap order | `POST /v1/pay/convert`      | `POST /transfer/open/institution/v1/pay/convert`      |
| Query swap order  | `GET /v1/pay/convert/order` | `GET /transfer/open/institution/v1/pay/convert/order` |

For complete institution API details, see [Institution API](/essentials/version/100/en/institutionalApi).

## Error Handling

For comprehensive error codes and resolution steps, refer to [Error Codes & Best Practices](/essentials/version/100/en/errorCodesBestPractices).

## Integration Checklist

* [ ] Retrieve available currency pairs from `GET /v1/pay/convert/pair`
* [ ] Implement quote retrieval with expiration handling
* [ ] Generate unique `clientReqId` for each swap request
* [ ] Create swap orders with valid quotes
* [ ] Implement query fallback for order confirmation
* [ ] Handle all failure scenarios gracefully
* [ ] Store order IDs for reconciliation
* [ ] Monitor conversion rates and limits

## Related Documentation

* [Authentication & Security](/essentials/version/100/en/authenticationSecurity)
* [Institution API](/essentials/version/100/en/institutionalApi)
* [Account Queries and Reconciliation](/essentials/version/100/en/accountBalanceReconciliation)
* [Error Codes & Best Practices](/essentials/version/100/en/errorCodesBestPractices)
* [General Overview](/essentials/version/100/en/generalOverview)


Built with [Mintlify](https://mintlify.com).