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

# Solana 兑换交易构建：Swap API

> 用 GET /swap 构建序列化的 Solana 兑换交易，然后从钱包签名并广播。包含滑点和优先费选项。

> [!NOTE]
>
> 本页介绍的是较早的 Solana Tracker Swap API（`swap-v2.solanatracker.io`）。它仍在运行，每笔兑换收取平台费。[Raptor](https://docs.solanatracker.io/cn/raptor/overview.md) 是另一款独立的兑换 API（`raptor.solanatracker.io`），目前免费，无需 API 密钥。

## 概览

swap 端点在 Solana 上构建代币兑换交易。您会收到一个序列化交易,您需要使用钱包签名并广播。

> [!NOTE]
>
> 此端点构建交易但不执行。您必须自行签名并发送交易。

## 支持的平台

* **Pump.fun** - 上线平台代币
* **PumpSwap** - Pump.fun 流动性池
* **Orca** - 集中流动性
* **Meteora** - 动态池
* **Moonshot** - 新上线
* **Raydium** - V4 AMM、CPMM、Launchpad
* **Jupiter** - 聚合路由

## SDK 示例

```javascript JavaScript theme={null}
import { SolanaTracker } from 'solana-swap';

const tracker = new SolanaTracker('YOUR_API_KEY', 'YOUR_PRIVATE_KEY');

// Basic swap
const swap = await tracker.swap({
  from: 'So11111111111111111111111111111111111111112', // SOL
  to: '4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R',
  fromAmount: 0.1,
  slippage: 10,
  payer: 'YOUR_WALLET_ADDRESS',
  priorityFee: 0.000005,
  txVersion: 'v0'
});

console.log('Transaction:', swap.txn);
```

在这些 SDK 示例中,`slippage: 10` 表示 10%。

```python Python theme={null}
from solana_swap import SolanaTracker

tracker = SolanaTracker('YOUR_API_KEY', 'YOUR_PRIVATE_KEY')

# Basic swap
swap = tracker.swap(
    from_token='So11111111111111111111111111111111111111112',
    to_token='4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R',
    from_amount=0.1,
    slippage=10,
    payer='YOUR_WALLET_ADDRESS',
    priority_fee=0.000005,
    tx_version='v0'
)

print('Transaction:', swap['txn'])
```

```bash cURL theme={null}
curl -X GET "https://swap-v2.solanatracker.io/swap?from=So11111111111111111111111111111111111111112&to=4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R&fromAmount=0.1&slippage=10&payer=YOUR_WALLET_ADDRESS&priorityFee=0.000005&txVersion=v0"
```

## 关键参数

### 金额格式

`fromAmount` 参数接受:

* **数值**: `1`、`0.5` - 精确金额
* **自动**: `"auto"` - 整个钱包余额
* **百分比**: `"50%"`、`"25%"` - 余额的百分比

### 优先费

```javascript theme={null}
// Manual fee
{ priorityFee: 0.000005 }

// Automatic with level
{ 
  priorityFee: "auto",
  priorityFeeLevel: "high" // min, low, medium, high, veryHigh, unsafeMax
}
```

### 合作伙伴 / 推荐费

添加您自己的合作伙伴或推荐费用以实现盈利:

```javascript theme={null}
{
  fee: "YOUR_WALLET:0.1", // 0.1% to your wallet
  feeType: "add" // or "deduct" (SOL only)
}
```

## 示例

### 使用自动金额的兑换

```javascript theme={null}
// Swap entire balance
const swap = await tracker.swap({
  from: 'So11111111111111111111111111111111111111112',
  to: '4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R',
  fromAmount: "auto",
  slippage: 15,
  payer: 'YOUR_WALLET_ADDRESS'
});
```

### 使用百分比的兑换

```javascript theme={null}
// Swap 50% of balance
const swap = await tracker.swap({
  from: 'TOKEN_ADDRESS',
  to: 'So11111111111111111111111111111111111111112',
  fromAmount: "50%",
  slippage: 10,
  payer: 'YOUR_WALLET_ADDRESS'
});
```

### 自定义费用的兑换

```javascript theme={null}
// Add 0.1% fee
const swap = await tracker.swap({
  from: 'So11111111111111111111111111111111111111112',
  to: '4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R',
  fromAmount: 1,
  slippage: 10,
  payer: 'YOUR_WALLET_ADDRESS',
  fee: 'YOUR_FEE_WALLET:0.1',
  feeType: 'add'
});
```

## 响应结构

```json theme={null}
{
  "txn": "BASE64_ENCODED_TRANSACTION",
  "rate": {
    "amountIn": 0.1,
    "amountOut": 81.631985,
    "minAmountOut": 73.4687865,
    "currentPrice": 0.012219167460548153,
    "executionPrice": 0.010997250714493338,
    "priceImpact": 0.002517,
    "fee": 0.000005,
    "platformFee": 9000000,
    "platformFeeUI": 0.009
  },
  "timeTaken": 0.016,
  "type": "v0"
}
```

## Solana Tracker 平台费

标准费用:交易金额的 **0.5%**

* 从输出中扣除
* 在 `platformFee`(lamports)和 `platformFeeUI`(SOL)中显示
* 提供成交量折扣

> [!TIP]
>
> 联系 [swap-api@solanatracker.io](mailto:swap-api@solanatracker.io) 了解成交量定价

## 常见错误

| 错误 | 解决方案 |
| - | - |
| 无效代币地址 | 验证地址是否有效 |
| 无效金额 | 使用数字、"auto" 或百分比 |
| 无效滑点 | 设为 0-100 之间 |
| 代币没有池 | 代币可能已下架 |
| 流动性不足 | 尝试较小金额 |

## 下一步

> [card] [Rate 端点](https://docs.solanatracker.io/cn/swap-api/rate.md)
>
> 在兑换前获取报价

> [card] [JavaScript SDK](https://github.com/YZYLAB/solana-swap)
>
> 安装 SDK


## OpenAPI

````yaml openapi.json get /swap
openapi: 3.1.0
info:
  title: Solana Tracker - Swap API
  description: >-
    The Solana Tracker Swap API offers seamless, zero-delay access to Solana's
    dynamic token marketplace. Trade tokens the moment they launch with our
    high-performance infrastructure. Supports Pump.fun, PumpSwap, Moonshot,
    Boop, Orca, Meteora, Raydium, and any pool supported by Jupiter.
  version: 2.0.0
  contact:
    name: Solana Tracker Support
    email: swap-api@solanatracker.io
    url: https://discord.com/invite/JH2e9rR9fc
  x-fees:
    standard: 0.5%
    highVolume: 0-0.5%
servers:
  - url: https://swap-v2.solanatracker.io
    description: Production server
security: []
tags:
  - name: Swap
    description: Token swap operations
  - name: Rate
    description: Rate and price quote operations
externalDocs:
  description: Full API Documentation
  url: https://docs.solanatracker.io/swap-api
paths:
  /swap:
    get:
      summary: Build Swap Transaction
      description: >-
        Build a swap transaction on Solana. Sign and send the transaction using
        your own wallet infrastructure.
      operationId: swapGet
      parameters:
        - name: from
          in: query
          required: true
          description: The base token address
          schema:
            type: string
            example: So11111111111111111111111111111111111111112
        - name: to
          in: query
          required: true
          description: The quote token address
          schema:
            type: string
            example: 4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R
        - name: fromAmount
          in: query
          required: true
          description: >-
            The amount of the base token to swap. Accepts numeric value, 'auto'
            for full wallet balance, or percentage like '50%'
          schema:
            oneOf:
              - type: number
                example: 1
              - type: string
                enum:
                  - auto
                example: auto
              - type: string
                pattern: ^[0-9]+(\.[0-9]+)?%$
                example: 50%
        - name: slippage
          in: query
          required: true
          description: >-
            Maximum acceptable slippage percentage or 'auto' for dynamic
            slippage (Beta)
          schema:
            oneOf:
              - type: number
                minimum: 0
                maximum: 100
                example: 10
              - type: string
                enum:
                  - auto
        - name: payer
          in: query
          required: true
          description: Public key of the wallet sending the transaction
          schema:
            type: string
            example: arsc4jbDnzaqcCLByyGo7fg7S2SmcFsWUzQuDtLZh2y
        - name: priorityFee
          in: query
          required: false
          description: Amount in SOL to increase transaction priority or 'auto'
          schema:
            oneOf:
              - type: number
                example: 0.000005
              - type: string
                enum:
                  - auto
        - name: priorityFeeLevel
          in: query
          required: false
          description: Priority level when priorityFee is set to 'auto'
          schema:
            type: string
            enum:
              - min
              - low
              - medium
              - high
              - veryHigh
              - unsafeMax
            default: medium
        - name: txVersion
          in: query
          required: false
          description: Transaction version
          schema:
            type: string
            enum:
              - v0
              - legacy
            default: v0
        - name: fee
          in: query
          required: false
          description: Custom fee for your users in format 'WALLET_ADDRESS:PERCENTAGE'
          schema:
            type: string
            pattern: ^[a-zA-Z0-9]+:[0-9]+(\.[0-9]+)?$
            example: arsc4jbDnzaqcCLByyGo7fg7S2SmcFsWUzQuDtLZh2y:0.1
        - name: customTip
          in: query
          required: false
          description: >-
            Custom tip for Jito or similar services in format
            'WALLET_ADDRESS:SOL_AMOUNT'
          schema:
            type: string
            pattern: ^[a-zA-Z0-9]+:[0-9]+(\.[0-9]+)?$
        - name: feeType
          in: query
          required: false
          description: >-
            Fee application type. 'deduct' option is only used when the from
            address is SOL
          schema:
            type: string
            enum:
              - add
              - deduct
            default: add
        - name: onlyDirectRoutes
          in: query
          required: false
          description: Disable multi-hop swaps
          schema:
            type: boolean
            default: false
      responses:
        '200':
          description: Successful swap transaction
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SwapResponse'
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
components:
  schemas:
    SwapResponse:
      type: object
      properties:
        txn:
          type: string
          description: Base64 encoded transaction
          example: BASE64_TX
        rate:
          type: object
          properties:
            amountIn:
              type: number
              description: Amount of input token
              example: 1
            amountOut:
              type: number
              description: Amount of output token
              example: 81.631985
            minAmountOut:
              type: number
              description: Minimum amount out after slippage
              example: 73.4687865
            currentPrice:
              type: number
              description: Current market price
              example: 0.012219167460548153
            executionPrice:
              type: number
              description: Actual execution price
              example: 0.010997250714493338
            priceImpact:
              type: number
              description: Price impact as a decimal
              example: 0.002517
            fee:
              type: number
              description: Transaction fee
              example: 0.000005
            baseCurrency:
              type: object
              properties:
                mint:
                  type: string
                  description: Base token mint address
                decimals:
                  type: integer
                  description: Base token decimals
            quoteCurrency:
              type: object
              properties:
                mint:
                  type: string
                  description: Quote token mint address
                decimals:
                  type: integer
                  description: Quote token decimals
            platformFee:
              type: integer
              description: Platform fee in lamports
              example: 9000000
            platformFeeUI:
              type: number
              description: Platform fee in SOL
              example: 0.009
        timeTaken:
          type: number
          description: Time taken for the operation in seconds
          example: 0.016
        type:
          type: string
          enum:
            - v0
            - legacy
          description: Transaction type
          example: legacy
    Error:
      type: object
      required:
        - error
      properties:
        error:
          type: string
          description: Error message
          examples:
            - An internal error occurred
            - Invalid or missing 'from' or 'to' token address
            - Invalid amount
            - Invalid slippage tolerance (should be between 0 and 100%)
        details:
          type: string
          description: Additional error details
          examples:
            - Unable to fetch pools for token
            - Token has no pools
            - No pools with liquidity found

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.