> For the complete documentation index, see [llms.txt](https://docs.heyhal.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.heyhal.xyz/api-documentation/swap-tokens.md).

# Swap Tokens

## Swap Token

Endpoint: <mark style="color:yellow;">POST /api/v1/coin/swap</mark>

### Description

This endpoint generates a serialized transaction for token swaps (buy/sell) on the platform. It handles both initial minting with buys and regular trading operations. The endpoint returns a serialized transaction that must be signed and sent by the client.

**Authentication Required:** Yes

**Type:** Bearer Token (JWT)

**Request Headers**

**Content-Type:** application/json

**Authorization:** Bearer \<your\_jwt\_token>

**Body Parameters**

| Parameter | Type   | Required | Description                                      |
| --------- | ------ | -------- | ------------------------------------------------ |
| token     | string | Yes      | The mint address of the token                    |
| amount    | string | Yes      | The amount to swap in lamports                   |
| type      | string | Yes      | The type of swap ("buy" or "sell")               |
| memo      | string | No       | Optional memo for tracking referrals and bonuses |

**Example Request Body:**

{

&#x20; "token": "TokenMintAddress123...",

&#x20; "amount": "1000000000",

&#x20; "type": "buy",

&#x20; "memo": "home"

}

**Response**

Success Response:

Status Code: 200 OK

Content-Type: application/json

{

&#x20; "serializedTransaction": "base58EncodedSerializedTransaction..."

}

**Error Response:**

Status Code: 500 Internal Server Error

{

&#x20; "error": "An internal error occurred. Please try again later."

}

**Example Usage:**

async function swapToken(

&#x20; tokenMintAddress: string,&#x20;

&#x20; amount: string,&#x20;

&#x20; type: 'buy' | 'sell',

&#x20; memo?: string

) {

&#x20; try {

&#x20;   const response = await fetch('<https://api.cybers.app/api/v1/coin/swap>', {

&#x20;     method: 'POST',

&#x20;     headers: {

&#x20;       'Content-Type': 'application/json',

&#x20;       'Authorization': \`Bearer ${jwt}\`

&#x20;     },

&#x20;     body: JSON.stringify({

&#x20;       token: tokenMintAddress,

&#x20;       amount,

&#x20;       type,

&#x20;       memo

&#x20;     })

&#x20;   });

&#x20;   if (!response.ok) {

&#x20;     throw new Error(\`HTTP error! status: ${response.status}\`);

&#x20;   }

&#x20;   const { serializedTransaction } = await response.json();

&#x20;  &#x20;

&#x20;   // Sign and send transaction using wallet

&#x20;   const signedTx = await wallet.signTransaction(

&#x20;     Transaction.from(bs58.decode(serializedTransaction))

&#x20;   );

&#x20;  &#x20;

&#x20;   const signature = await connection.sendRawTransaction(

&#x20;     signedTx.serialize()

&#x20;   );

&#x20;  &#x20;

&#x20;   return signature;

&#x20; } catch (error) {

&#x20;   console.error('Error in swap operation:', error);

&#x20;   throw error;

&#x20; }

}

### Implementation Notes

Transaction Flow -&#x20;

#### For buy operations:

If token is not minted, creates mint + buy transaction

If token exists, creates buy transaction only

**For sell operations:**

Creates sell transaction

**Memo Usage:**

Memos are included in the transaction for tracking

Used internally for referral points and bonus calculations

Visible on-chain for transaction tracking

**Transaction Handling:**

Returns serialized transaction only

Client must sign and send the transaction

All necessary instructions are bundled in single transaction

**Best Practices:**

Always verify transaction before signing

Implement proper error handling

Consider price impact for large swaps

Handle network congestion gracefully

**Related Operations:**

Use GET /api/v1/coin/reserves to check liquidity before swap

Monitor transaction status after sending

Consider implementing retry logic for failed transactions

<br>
