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

# Swap APIs

> Atomic HTLC swap initiation, execution, and status — used by the desktop app and direct node integrations

## Overview

The Swap APIs implement the **atomic swap protocol** used by the KaleidoSwap Desktop App. Swaps execute via Hash Time-Locked Contracts (HTLCs) on the Lightning Network — both sides lock assets simultaneously, so either the full exchange completes or funds are returned. There is no counterparty risk.

To use these endpoints you need:

* A running **RGB Lightning Node (RLN)** to whitelist and route the HTLC.
* A **WebSocket connection** to the maker for live price streaming and `rfq_id` generation.

If you are building a web integration without a full node, use the [order-based swap flow](/api-reference/market-apis) via Market APIs instead, and refer to the [Swap Protocol](/api-reference/swap-protocol) for a comparison of both models.

**Base URL:** `https://api.signet.kaleidoswap.com/api/v1` (Signet) or `https://api.regtest.kaleidoswap.com/api/v1` (Regtest)

***

***

## Get Node Information

### Endpoint

**`GET /api/v1/swaps/nodeinfo`**

### Description

Retrieve information about the RGB Lightning Node, such as its identifier, alias, and current state.

### Response Structure

* **`node_id`**: The unique identifier of the node.
* **`alias`**: The human-readable name of the node.
* **`color`**: The color code associated with the node.
* **`num_peers`**: Number of peers connected to the node.
* **`num_channels`**: Number of active channels.
* **`block_height`**: Current blockchain height the node is synced to.
* **`synced_to_chain`**: Boolean indicating if the node is fully synced to the blockchain.

### Example Response

```json theme={null}
{
  "node_id": "03e7156ae33b0a208d0744199163177e909e80176e55d97a2f221ede0f934dd9ad",
  "alias": "RGB-LSP-Node",
  "color": "#000000",
  "num_peers": 5,
  "num_channels": 10,
  "block_height": 700000,
  "synced_to_chain": true
}
```

***

## Real-time Price Updates

### WebSocket Endpoint

| Environment | URL                                                        |
| ----------- | ---------------------------------------------------------- |
| **Regtest** | `wss://api.regtest.kaleidoswap.com/ws/{client_id}`         |
| **Signet**  | `wss://api.signet.kaleidoswap.com/ws/{client_id}`          |
| **Mainnet** | `wss://api.kaleidoswap.com/ws/{client_id}` *(coming soon)* |

### Description

Establish a WebSocket connection to subscribe to real-time price updates for specific trading pairs.

### Connection

* Replace `{client_id}` with a unique identifier for your client.

### Subscription Format

To subscribe to a trading pair, send a JSON message with the following format:

```json theme={null}
{
  "action": "subscribe",
  "pair": "BTC/USDT"
}
```

To unsubscribe from a trading pair:

```json theme={null}
{
  "action": "unsubscribe",
  "pair": "BTC/USDT"
}
```

### Response Format

Price updates are streamed as JSON objects:

* `action`: The action performed (e.g., `priceUpdate`).
* `data`: The details of the price update.

### Example Response

```json theme={null}
{
  "action": "price_update",
  "data": {
    "rfq_id": "13d4777c-ae96-4858-9c7c-3ca730c5039a",
    "price_buy": 59507000000,
    "price_sell": 59508000000,
    "fee_base": 100,
    "fee_rate": 0.1,
    "price_precision": 6,
    "base_precision": 8,
    "pair": "BTC/USDT",
    "timestamp": 1630296243,
    "expires_at": 1630296248
  }
}
```

### Field Descriptions

* **`rfq_id`**: The `request_for_quotation_id`, a unique identifier generated by the maker. This ID is crucial for initiating swaps and must be passed in the `init` endpoint.
* **`price_buy`**: The buy price for the trading pair.
* **`price_sell`**: The sell price for the trading pair.
* **`price_precision`**: The number of decimal places to which the price is quoted, relevant to the quote asset. For example, if `pricePrecision` is `6` for the BTC/USDT pair, it indicates that the USDT is quoted to six decimal places.
* **`base_precision`**: The number of decimal places to which the base asset is quoted. For example, if `basePrecision` is `8` for the BTC/USDT pair, it indicates that BTC is quoted to eight decimal places.
* **`pair`**: The trading pair, such as BTC/USDT.
* **`timestamp`**: The timestamp when the price update was generated in unix time.
* **`expires_at`**: The timestamp when the `rfqId` will expire in unix time.

### Price Precision Note

* Prices provided in the response do not reflect the precision of the base asset. For instance, in a BTC/USDT pair, the base asset (BTC) is always denominated in satoshis, and the quote asset (USDT) price precision is found in the update. For example, a `buyPrice` of `59507000000` unit for a size of `100000000` sats (1 BTC) corresponds to `59507` USDT, considering the `pricePrecision` of `8`.

### Additional Notes:

* The server validates the requested pair against the list of available pairs. If an invalid pair is requested, the subscription will be ignored.
* When BTC is in a pair, it is always denominated in satoshis (sats) with a precision of `0`.
* Clients can subscribe to multiple pairs by sending multiple subscription messages.
* The WebSocket connection will remain open until the client disconnects or a network error occurs.

***

## Initiate Swap

### Endpoint

`POST /api/v1/swaps/init`

### Description

Initiate a swap based on the price update received via WebSocket. This endpoint locks the price and prepares the swap for execution.

### Request Body

| Field         | Type    | Description                                        |
| ------------- | ------- | -------------------------------------------------- |
| `rfq_id`      | String  | The ID of the price update received via WebSocket. |
| `from_asset`  | String  | The RGB asset ID to swap from.                     |
| `from_amount` | Integer | The amount of the asset to swap from.\*            |
| `to_asset`    | String  | The RGB asset ID to swap to.                       |
| `to_amount`   | Integer | The amount of the asset to swap to.\*              |

\*If the asset is BTC, the amount should be specified in **millisatoshis (msat)**. For other assets, the amount should be provided in the asset’s native unit without considering precision.

### Example Request

```json theme={null}
{
  "rfq_id": "8e6635fb-ab37-4aed-89f4-bc9c98fb8b49",
  "from_asset": "btc", 
  "from_amount": 1000000, 
  "to_asset": "rgb:2V2f58W-Tabtk3J4j-qGVQQwPWt-ksbujLNxx-x1BMTNBEf-KVsg2j3",
  "to_amount": 587770
}
```

### Response Structure

* `swapstring`: A string representation of the swap to be executed.
* `payment_hash`: The payment hash associated with the swap.

### Example Response

```json theme={null}
{
  "swapstring": "1000000/btc/587770/rgb:2NZGjyz-pJePUgegh-RLHbpx1Hy-iZMagWiZZ-qY4AxGymW-yCEYwwB/be35403fcd85722cb0373db0527a452ce9c2eb23d3ec489af8e33ffb57d5271e",
  "payment_hash": "be35403fcd85722cb0373db0527a452ce9c2eb23d3ec489af8e33ffb57d5271e"
}
```

### Additional Notes

* The precision for an RGB asset can be obtained using the `/assets` API on the maker's node. If the client has the same asset, the precision can also be retrieved via the node API.
* The swapstring returned by this endpoint needs to be whitelisted using the `/taker` API of the RGB Lightning Node (RLN) of the client before executing the swap.
* In this example, the user is selling 1,000 sats for 0.5877 USDT (using the RGB asset `rgb:2NZGjyz-pJePUgegh-RLHbpx1Hy-iZMagWiZZ-qY4AxGymW-yCEYwwB`).

***

## Execute Swap

### Endpoint

`POST /api/v1/swaps/execute`

### Description

Execute the swap after it has been initiated and validated.

### Request Body

| Field          | Type   | Description                                   |
| -------------- | ------ | --------------------------------------------- |
| `swapstring`   | String | The swap string generated by `init` endpoint. |
| `taker_pubkey` | String | The public key of the taker.                  |
| `payment_hash` | String | The payment hash associated with the swap.    |

### Example Request

```json theme={null}
{
  "swapstring": "1000000/btc/587770/rgb:2NZGjyz-pJePUgegh-RLHbpx1Hy-iZMagWiZZ-qY4AxGymW-yCEYwwB/be35403fcd85722cb0373db0527a452ce9c2eb23d3ec489af8e33ffb57d5271e",
  "taker_pubkey": "03e7156ae33b0a208d0744199163177e909e80176e55d97a2f221ede0f934dd9ad",
  "payment_hash": "be35403fcd85722cb0373db0527a452ce9c2eb23d3ec489af8e33ffb57d5271e"
}
```

### Response Structure

* `status`: Status code of the swap execution.
* `message`: Additional details about the execution.

### Example Response

```json theme={null}
{
  "status": 200,
  "message": "Swap executed successfully"
}
```

***

## Get Swap Status

### Endpoint

`GET /api/v1/swaps/status`

### Description

Retrieve the current status of a swap using the associated `payment_hash`.

### Query Parameters

* `payment_hash` (string, required): The payment hash of the swap whose status is to be retrieved.

### Example Request

```bash theme={null}
GET /api/v1/swaps/status?payment_hash=7c2c95b9c2aa0a7d140495b664de7973b76561de833f0dd84def3efa08941664
```

### Response

* `swap`: An object containing detailed information about the swap.

### Example Response

```json theme={null}
{
  "swap": {
    "qty_from": 1000000,
    "qty_to": 587770,
    "from_asset": "btc",
    "to_asset": "rgb:2V2f58W-Tabtk3J4j-qGVQQwPWt-ksbujLNxx-x1BMTNBEf-KVsg2j3",
    "payment_hash": "7c2c95b9c2aa0a7d140495b664de7973b76561de833f0dd84def3efa08941664",
    "status": "Pending",
    "requested_at": 1691160765,
    "initiated_at": 1691168512,
    "expires_at": 1691172703,
    "completed_at": 1691171075
  }
}
```

### Swap Object Schema

* **`qty_from`** (`integer`): The quantity of the asset being swapped from. Example: `30`
* **`qty_to`** (`integer`): The quantity of the asset being swapped to. Example: `10`
* **`from_asset`** (`string`): The RGB asset ID being swapped from. Example: `rgb:2dkSTbr-jFhznbPmo-TQafzswCN-av4gTsJjX-ttx6CNou5-M98k8Zd`
* **`to_asset`** (`string`): The RGB asset ID being swapped to. Example: `rgb:2eVw8uw-8G88LQ2tQ-kexM12SoD-nCX8DmQrw-yLMu6JDfK-xx1SCfc`
* **`payment_hash`** (`string`): The unique payment hash associated with the swap. Example: `7c2c95b9c2aa0a7d140495b664de7973b76561de833f0dd84def3efa08941664`
* **`status`** (`SwapStatus`): The current status of the swap. Possible values:
  * `Waiting`
  * `Pending`
  * `Succeeded`
  * `Expired`
  * `Failed`
* **`requested_at`** (`integer`): Unix timestamp when the swap was requested. Example: `1691160765`
* **`initiated_at`** (`integer`): Unix timestamp when the swap was initiated. Example: `1691168512`
* **`expires_at`** (`integer`): Unix timestamp when the swap expires. Example: `1691172703`
* **`completed_at`** (`integer`): Unix timestamp when the swap was completed. Example: `1691171075`

### Additional Notes

* The `status` field provides real-time updates on the swap's progress.
* Ensure that the `payment_hash` provided is accurate to retrieve the correct swap status.
* Time-related fields are in Unix timestamp format.
* The `SwapStatus` field in the `Swap` object can have one of the following values:
  * **`Waiting`**: The swap is awaiting initiation.
  * **`Pending`**: The swap has been initiated and is currently in progress.
  * **`Succeeded`**: The swap has been successfully completed.
  * **`Expired`**: The swap was not completed within the required timeframe.
  * **`Failed`**: The swap encountered an error and did not complete successfully.

***

For error details, refer to [Error Handling](/api-reference/error-handling).
