dex-execution

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

DEX Execution — Solana Swap Execution via Jupiter

DEX 执行 — 通过 Jupiter 执行 Solana 兑换

Execute token swaps on Solana through Jupiter, the dominant DEX aggregator routing across Raydium, Orca, Meteora, Phoenix, Lifinity, and 20+ other venues.
通过 Jupiter 在 Solana 上执行代币兑换。Jupiter 是占主导地位的 DEX 聚合器,可跨 Raydium、Orca、Meteora、Phoenix、Lifinity 等 20 多个交易场所进行路由。

Overview

概述

Jupiter aggregates liquidity across all major Solana DEXes to find optimal swap routes. A single swap may split across multiple pools and hop through intermediate tokens to minimize price impact. The Jupiter v6 API handles route discovery, transaction building, and fee optimization — your code handles quoting, user confirmation, signing, and submission.
Base URL:
https://quote-api.jup.ag/v6
Jupiter 聚合所有主要 Solana DEX 的流动性,以寻找最优兑换路径。单次兑换可能会拆分到多个池中,并经由中间代币跳转,以尽量降低价格影响。Jupiter v6 API 负责路径发现、交易构建和费用优化——你的代码负责报价、用户确认、签名和提交。
基础 URL:
https://quote-api.jup.ag/v6

Execution Pipeline

执行流程

Every swap follows this seven-step pipeline. Never skip steps 2-3 (display and confirm).
每次兑换都遵循以下七步流程。绝不能跳过第 2-3 步(展示和确认)。

Step 1 — Get Quote

第 1 步 — 获取报价

python
import httpx

params = {
    "inputMint": "So11111111111111111111111111111111111111112",   # SOL
    "outputMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", # USDC
    "amount": 1_000_000_000,  # 1 SOL in lamports
    "slippageBps": 50,        # 0.5%
}
resp = httpx.get("https://quote-api.jup.ag/v6/quote", params=params)
quote = resp.json()
python
import httpx

params = {
    "inputMint": "So11111111111111111111111111111111111111112",   # SOL
    "outputMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", # USDC
    "amount": 1_000_000_000,  # 1 SOL in lamports
    "slippageBps": 50,        # 0.5%
}
resp = httpx.get("https://quote-api.jup.ag/v6/quote", params=params)
quote = resp.json()

Step 2 — Display Quote to User

第 2 步 — 向用户展示报价

Always show these fields before proceeding:
FieldSource
Input amount
quote["inAmount"]
(in token decimals)
Output amount
quote["outAmount"]
Minimum received
quote["otherAmountThreshold"]
Price impact
quote["priceImpactPct"]
Route
quote["routePlan"]
— DEXes used
SlippageThe
slippageBps
you requested
继续操作前,始终向用户展示以下字段:
字段来源
输入金额
quote["inAmount"]
(按代币小数精度计)
输出金额
quote["outAmount"]
最低收到数量
quote["otherAmountThreshold"]
价格影响
quote["priceImpactPct"]
路径
quote["routePlan"]
— 使用的 DEX
滑点请求的
slippageBps

Step 3 — Require User Confirmation

第 3 步 — 要求用户确认

⚠️  SWAP PREVIEW
    Selling:   1.000 SOL
    Buying:    ~142.50 USDC
    Min recv:  141.79 USDC (0.5% slippage)
    Impact:    0.01%
    Route:     Raydium V4 → USDC

    Proceed? [y/N]
NEVER proceed without explicit "yes" from the user.
⚠️  SWAP PREVIEW
    Selling:   1.000 SOL
    Buying:    ~142.50 USDC
    Min recv:  141.79 USDC (0.5% slippage)
    Impact:    0.01%
    Route:     Raydium V4 → USDC

    Proceed? [y/N]
未经用户明确输入“yes”,绝不能继续执行。

Step 4 — Build Transaction

第 4 步 — 构建交易

python
swap_body = {
    "quoteResponse": quote,
    "userPublicKey": "YourPubkeyBase58...",
    "wrapAndUnwrapSol": True,
    "dynamicComputeUnitLimit": True,
    "prioritizationFeeLamports": "auto",
}
resp = httpx.post("https://quote-api.jup.ag/v6/swap", json=swap_body)
swap_data = resp.json()
swap_tx = swap_data["swapTransaction"]  # base64-encoded transaction
python
swap_body = {
    "quoteResponse": quote,
    "userPublicKey": "YourPubkeyBase58...",
    "wrapAndUnwrapSol": True,
    "dynamicComputeUnitLimit": True,
    "prioritizationFeeLamports": "auto",
}
resp = httpx.post("https://quote-api.jup.ag/v6/swap", json=swap_body)
swap_data = resp.json()
swap_tx = swap_data["swapTransaction"]  # base64-encoded transaction

Step 5 — Sign Transaction

第 5 步 — 签名交易

python
import base64
from solders.transaction import VersionedTransaction
from solders.keypair import Keypair

raw_tx = base64.b64decode(swap_tx)
tx = VersionedTransaction.from_bytes(raw_tx)
keypair = Keypair.from_base58_string(os.environ["WALLET_PRIVATE_KEY"])
tx.sign([keypair])
python
import base64
from solders.transaction import VersionedTransaction
from solders.keypair import Keypair

raw_tx = base64.b64decode(swap_tx)
tx = VersionedTransaction.from_bytes(raw_tx)
keypair = Keypair.from_base58_string(os.environ["WALLET_PRIVATE_KEY"])
tx.sign([keypair])

Step 6 — Submit Transaction

第 6 步 — 提交交易

python
rpc_url = os.environ.get("SOLANA_RPC_URL", "https://api.mainnet-beta.solana.com")
signed_bytes = bytes(tx)
payload = {
    "jsonrpc": "2.0", "id": 1,
    "method": "sendTransaction",
    "params": [
        base64.b64encode(signed_bytes).decode(),
        {"encoding": "base64", "skipPreflight": False,
         "maxRetries": 3, "preflightCommitment": "confirmed"}
    ],
}
resp = httpx.post(rpc_url, json=payload)
sig = resp.json()["result"]
print(f"Submitted: https://solscan.io/tx/{sig}")
python
rpc_url = os.environ.get("SOLANA_RPC_URL", "https://api.mainnet-beta.solana.com")
signed_bytes = bytes(tx)
payload = {
    "jsonrpc": "2.0", "id": 1,
    "method": "sendTransaction",
    "params": [
        base64.b64encode(signed_bytes).decode(),
        {"encoding": "base64", "skipPreflight": False,
         "maxRetries": 3, "preflightCommitment": "confirmed"}
    ],
}
resp = httpx.post(rpc_url, json=payload)
sig = resp.json()["result"]
print(f"Submitted: https://solscan.io/tx/{sig}")

Step 7 — Confirm Transaction

第 7 步 — 确认交易

python
import time

for attempt in range(30):
    payload = {
        "jsonrpc": "2.0", "id": 1,
        "method": "getSignatureStatuses",
        "params": [[sig], {"searchTransactionHistory": False}],
    }
    resp = httpx.post(rpc_url, json=payload)
    status = resp.json()["result"]["value"][0]
    if status and status.get("confirmationStatus") in ("confirmed", "finalized"):
        print(f"Confirmed at slot {status['slot']}")
        break
    time.sleep(2)
else:
    print("Transaction not confirmed within 60s — check explorer")
python
import time

for attempt in range(30):
    payload = {
        "jsonrpc": "2.0", "id": 1,
        "method": "getSignatureStatuses",
        "params": [[sig], {"searchTransactionHistory": False}],
    }
    resp = httpx.post(rpc_url, json=payload)
    status = resp.json()["result"]["value"][0]
    if status and status.get("confirmationStatus") in ("confirmed", "finalized"):
        print(f"Confirmed at slot {status['slot']}")
        break
    time.sleep(2)
else:
    print("Transaction not confirmed within 60s — check explorer")

Jupiter API v6 Endpoints

Jupiter API v6 端点

EndpointMethodPurpose
/quote
GETGet best-price quote with routing
/swap
POSTBuild a swap transaction from a quote
/swap-instructions
POSTGet individual instructions (advanced)
/price?ids=token1,token2
GETSimple price lookup (v2)
/tokens
GETList all supported tokens
See
references/jupiter_api.md
for full parameter and response documentation.
端点方法用途
/quote
GET获取带路由的最优价格报价
/swap
POST根据报价构建兑换交易
/swap-instructions
POST获取单独的指令(高级用法)
/price?ids=token1,token2
GET简单价格查询(v2)
/tokens
GET列出所有支持的代币
有关完整的参数和响应文档,请参阅
references/jupiter_api.md
。

Key Parameters

关键参数

Slippage (
slippageBps
)

滑点(
slippageBps
)

Token TypeRecommended RangeNotes
SOL, USDC, major tokens50-100 (0.5-1%)Stable liquidity
Mid-cap tokens100-300 (1-3%)Variable liquidity
PumpFun / meme tokens500-2000 (5-20%)Thin books, high volatility
New launches (<1h old)1000-3000 (10-30%)Extreme volatility
代币类型建议范围备注
SOL、USDC 和主要代币50-100(0.5-1%)流动性稳定
中市值代币100-300(1-3%)流动性波动
PumpFun / meme 代币500-2000(5-20%)订单簿薄,波动性高
新发行代币(上线不足 1 小时)1000-3000(10-30%)极端波动

Dynamic Slippage

动态滑点

Set
dynamicSlippage: true
in the swap request to let Jupiter auto-adjust slippage based on current market conditions. Preferred for most use cases.
在 swap 请求中设置
dynamicSlippage: true
,让 Jupiter 根据当前市场状况自动调整滑点。大多数使用场景都推荐采用此方式。

Priority Fees (
prioritizationFeeLamports
)

优先费(
prioritizationFeeLamports
)

Priority fees determine transaction ordering within a block.
LevelmicroLamportsWhen to Use
Low10,000-50,000Normal conditions
Medium50,000-200,000Moderate congestion
High200,000-1,000,000High congestion / time-sensitive
Urgent1,000,000-5,000,000Meme coin launches, NFT mints
Auto
"auto"
Jupiter estimates for you
Use
"auto"
for most cases. For fine-grained control, query Helius
getPriorityFeeEstimate
.
优先费决定区块内的交易排序。
级别microLamports使用场景
低10,000-50,000网络状况正常
中50,000-200,000中度拥堵
高200,000-1,000,000严重拥堵或时间敏感
紧急1,000,000-5,000,000Meme 代币发行、NFT mint
自动
"auto"
由 Jupiter 估算
大多数情况下应使用
"auto"
。如需精细控制,可查询 Helius
getPriorityFeeEstimate
。

Other Parameters

其他参数

  • onlyDirectRoutes
    : Skip multi-hop routing. Faster but may get worse price.
  • asLegacyTransaction
    : Use legacy format instead of versioned transactions. Required for some older wallets.
  • maxAccounts
    : Limit accounts in transaction (default 64). Lower values reduce route options but improve confirmation reliability.
  • platformFeeBps
    : Integrator fee in basis points. Taken from output amount.
  • wrapAndUnwrapSol
    : Auto wrap/unwrap SOL ↔ wSOL (default true).
  • dynamicComputeUnitLimit
    : Auto-set compute budget based on simulation.
  • onlyDirectRoutes
    :跳过多跳路由。速度更快,但价格可能更差。
  • asLegacyTransaction
    :使用旧版格式而非 versioned transaction。某些旧版钱包需要此格式。
  • maxAccounts
    :限制交易中的账户数(默认 64)。值越低,可选路径越少,但确认可靠性更高。
  • platformFeeBps
    :以基点表示的集成商费用,从输出金额中扣除。
  • wrapAndUnwrapSol
    :自动包装或解包 SOL ↔ wSOL(默认 true)。
  • dynamicComputeUnitLimit
    :根据模拟结果自动设置计算预算。

Priority Fee Estimation

优先费估算

python
undefined
python
undefined

Using Helius getPriorityFeeEstimate

Using Helius getPriorityFeeEstimate

helius_url = f"https://mainnet.helius-rpc.com/?api-key={HELIUS_KEY}" payload = { "jsonrpc": "2.0", "id": 1, "method": "getPriorityFeeEstimate", "params": [{"accountKeys": [input_mint, output_mint], "options": {"recommended": True}}], } resp = httpx.post(helius_url, json=payload) fee = resp.json()["result"]["priorityFeeEstimate"]
undefined
helius_url = f"https://mainnet.helius-rpc.com/?api-key={HELIUS_KEY}" payload = { "jsonrpc": "2.0", "id": 1, "method": "getPriorityFeeEstimate", "params": [{"accountKeys": [input_mint, output_mint], "options": {"recommended": True}}], } resp = httpx.post(helius_url, json=payload) fee = resp.json()["result"]["priorityFeeEstimate"]
undefined

Transaction Confirmation Strategy

交易确认策略

See
references/transaction_lifecycle.md
for the full Solana transaction lifecycle.
  1. Submit with
    skipPreflight: False
    to catch obvious errors
  2. Poll
    getSignatureStatuses
    every 2 seconds for up to 60 seconds
  3. If not confirmed: rebuild transaction with fresh blockhash and retry (max 3 attempts)
  4. Blockhash expiry: transactions expire ~60 seconds after blockhash was fetched
  5. Final check: verify token balance changed as expected
有关完整的 Solana 交易生命周期,请参阅
references/transaction_lifecycle.md
。
  1. 提交时使用
    skipPreflight: False
    ,以捕获明显的错误
  2. 每 2 秒轮询一次
    getSignatureStatuses
    ,最长持续 60 秒
  3. 如果未确认:使用新的 blockhash 重建交易并重试(最多 3 次)
  4. Blockhash 过期:交易在获取 blockhash 后约 60 秒过期
  5. 最终检查:验证代币余额是否按预期发生变化

Error Handling

错误处理

ErrorCauseRecovery
"Slippage tolerance exceeded"
Price moved beyond slippageBpsIncrease slippage or retry
"Insufficient funds"
Not enough input token or SOL for feesCheck balance before quoting
"Transaction expired"
Blockhash too oldRebuild with fresh blockhash
"Transaction simulation failed"
Various — check logsParse simulation logs for root cause
"Too many accounts"
Route uses too many accountsSet
maxAccounts
lower or use
onlyDirectRoutes
HTTP 429Rate limitedBack off and retry with exponential delay
HTTP 400
"No route found"
No liquidity path existsCheck token mints are correct, try larger slippage
错误原因恢复方式
"Slippage tolerance exceeded"
价格变动超出
slippageBps
提高滑点或重试
"Insufficient funds"
输入代币或用于支付费用的 SOL 不足报价前检查余额
"Transaction expired"
Blockhash 过旧使用新的 blockhash 重建交易
"Transaction simulation failed"
多种原因——检查日志解析模拟日志以找出根本原因
"Too many accounts"
路径使用的账户过多将
maxAccounts
设得更低,或使用
onlyDirectRoutes
HTTP 429受到速率限制指数退避后重试
HTTP 400
"No route found"
不存在流动性路径检查代币 mint 是否正确,尝试更大的滑点

Safety Requirements

安全要求

These are non-negotiable requirements for any execution code.
  1. ALWAYS show quote details (amounts, price impact, route) before execution
  2. ALWAYS require explicit user confirmation — never auto-execute
  3. Default to simulation mode — do not sign or submit unless explicitly enabled
  4. Never store or log private keys — load from env vars, use immediately, discard
  5. Never use 100% slippage — this is a common scam/exploit vector
  6. Verify token addresses — confirm mints match expected tokens before swapping
  7. Check price impact — warn if >2%, block if >10% unless user overrides
  8. Maintain SOL reserve — keep 0.05 SOL minimum for rent and future fees
See
references/safety_checklist.md
for the complete pre/during/post execution checklist.
这些是任何执行代码都必须满足的不可协商要求。
  1. 始终展示报价详情(金额、价格影响和路径),然后再执行
  2. 始终要求用户明确确认——绝不自动执行
  3. 默认使用模拟模式——除非明确启用,否则不得签名或提交
  4. 绝不存储或记录私钥——从环境变量加载,使用后立即丢弃
  5. 绝不使用 100% 滑点——这是常见的诈骗和漏洞利用路径
  6. 验证代币地址——兑换前确认 mint 与预期代币一致
  7. 检查价格影响——超过 2% 时发出警告,超过 10% 时阻止执行,除非用户明确覆盖
  8. 保留 SOL 储备——至少保留 0.05 SOL,用于 rent 和未来费用
有关完整的执行前、执行中和执行后验证清单,请参阅
references/safety_checklist.md
。

Integration with Other Skills

与其他 Skill 的集成

SkillIntegration
slippage-modeling
Estimate optimal slippageBps based on token liquidity profile
liquidity-analysis
Verify pool depth supports trade size before quoting
position-sizing
Calculate trade amount based on risk parameters
risk-management
Enforce portfolio-level exposure limits before execution
jupiter-api
Underlying API documentation for Jupiter endpoints
helius-api
Priority fee estimation and transaction monitoring
Skill集成方式
slippage-modeling
根据代币流动性特征估算最佳
slippageBps
liquidity-analysis
报价前验证池深度足以支持交易规模
position-sizing
根据风险参数计算交易金额
risk-management
执行前实施投资组合层面的风险敞口限制
jupiter-api
Jupiter 端点的底层 API 文档
helius-api
优先费估算和交易监控

Files

文件

References

引用

  • references/jupiter_api.md
    — Complete Jupiter v6 API parameter and response reference
  • references/transaction_lifecycle.md
    — Solana transaction lifecycle, priority fees, retry strategies
  • references/safety_checklist.md
    — Pre/during/post execution verification checklist
  • references/jupiter_api.md
    — 完整的 Jupiter v6 API 参数和响应参考
  • references/transaction_lifecycle.md
    — Solana 交易生命周期、优先费和重试策略
  • references/safety_checklist.md
    — 执行前、执行中和执行后的验证清单

Scripts

脚本

  • scripts/get_quote.py
    — Fetch and display Jupiter swap quotes with route analysis
  • scripts/simulate_swap.py
    — Build and simulate swap transactions without submitting
  • scripts/get_quote.py
    — 获取并展示 Jupiter 兑换报价及路径分析
  • scripts/simulate_swap.py
    — 构建并模拟兑换交易,但不提交