dex-execution
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDEX 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/v6Jupiter 聚合所有主要 Solana DEX 的流动性,以寻找最优兑换路径。单次兑换可能会拆分到多个池中,并经由中间代币跳转,以尽量降低价格影响。Jupiter v6 API 负责路径发现、交易构建和费用优化——你的代码负责报价、用户确认、签名和提交。
基础 URL:
https://quote-api.jup.ag/v6Execution 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:
| Field | Source |
|---|---|
| Input amount | |
| Output amount | |
| Minimum received | |
| Price impact | |
| Route | |
| Slippage | The |
继续操作前,始终向用户展示以下字段:
| 字段 | 来源 |
|---|---|
| 输入金额 | |
| 输出金额 | |
| 最低收到数量 | |
| 价格影响 | |
| 路径 | |
| 滑点 | 请求的 |
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 transactionpython
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 transactionStep 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 端点
| Endpoint | Method | Purpose |
|---|---|---|
| GET | Get best-price quote with routing |
| POST | Build a swap transaction from a quote |
| POST | Get individual instructions (advanced) |
| GET | Simple price lookup (v2) |
| GET | List all supported tokens |
See for full parameter and response documentation.
references/jupiter_api.md| 端点 | 方法 | 用途 |
|---|---|---|
| GET | 获取带路由的最优价格报价 |
| POST | 根据报价构建兑换交易 |
| POST | 获取单独的指令(高级用法) |
| GET | 简单价格查询(v2) |
| GET | 列出所有支持的代币 |
有关完整的参数和响应文档,请参阅 。
references/jupiter_api.mdKey Parameters
关键参数
Slippage (slippageBps
)
slippageBps滑点(slippageBps
)
slippageBps| Token Type | Recommended Range | Notes |
|---|---|---|
| SOL, USDC, major tokens | 50-100 (0.5-1%) | Stable liquidity |
| Mid-cap tokens | 100-300 (1-3%) | Variable liquidity |
| PumpFun / meme tokens | 500-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 in the swap request to let Jupiter auto-adjust slippage based on current market conditions. Preferred for most use cases.
dynamicSlippage: true在 swap 请求中设置 ,让 Jupiter 根据当前市场状况自动调整滑点。大多数使用场景都推荐采用此方式。
dynamicSlippage: truePriority Fees (prioritizationFeeLamports
)
prioritizationFeeLamports优先费(prioritizationFeeLamports
)
prioritizationFeeLamportsPriority fees determine transaction ordering within a block.
| Level | microLamports | When to Use |
|---|---|---|
| Low | 10,000-50,000 | Normal conditions |
| Medium | 50,000-200,000 | Moderate congestion |
| High | 200,000-1,000,000 | High congestion / time-sensitive |
| Urgent | 1,000,000-5,000,000 | Meme coin launches, NFT mints |
| Auto | | Jupiter estimates for you |
Use for most cases. For fine-grained control, query Helius .
"auto"getPriorityFeeEstimate优先费决定区块内的交易排序。
| 级别 | microLamports | 使用场景 |
|---|---|---|
| 低 | 10,000-50,000 | 网络状况正常 |
| 中 | 50,000-200,000 | 中度拥堵 |
| 高 | 200,000-1,000,000 | 严重拥堵或时间敏感 |
| 紧急 | 1,000,000-5,000,000 | Meme 代币发行、NFT mint |
| 自动 | | 由 Jupiter 估算 |
大多数情况下应使用 。如需精细控制,可查询 Helius 。
"auto"getPriorityFeeEstimateOther Parameters
其他参数
- : Skip multi-hop routing. Faster but may get worse price.
onlyDirectRoutes - : Use legacy format instead of versioned transactions. Required for some older wallets.
asLegacyTransaction - : Limit accounts in transaction (default 64). Lower values reduce route options but improve confirmation reliability.
maxAccounts - : Integrator fee in basis points. Taken from output amount.
platformFeeBps - : Auto wrap/unwrap SOL ↔ wSOL (default true).
wrapAndUnwrapSol - : Auto-set compute budget based on simulation.
dynamicComputeUnitLimit
- :跳过多跳路由。速度更快,但价格可能更差。
onlyDirectRoutes - :使用旧版格式而非 versioned transaction。某些旧版钱包需要此格式。
asLegacyTransaction - :限制交易中的账户数(默认 64)。值越低,可选路径越少,但确认可靠性更高。
maxAccounts - :以基点表示的集成商费用,从输出金额中扣除。
platformFeeBps - :自动包装或解包 SOL ↔ wSOL(默认 true)。
wrapAndUnwrapSol - :根据模拟结果自动设置计算预算。
dynamicComputeUnitLimit
Priority Fee Estimation
优先费估算
python
undefinedpython
undefinedUsing 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"]
undefinedhelius_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"]
undefinedTransaction Confirmation Strategy
交易确认策略
See for the full Solana transaction lifecycle.
references/transaction_lifecycle.md- Submit with to catch obvious errors
skipPreflight: False - Poll every 2 seconds for up to 60 seconds
getSignatureStatuses - If not confirmed: rebuild transaction with fresh blockhash and retry (max 3 attempts)
- Blockhash expiry: transactions expire ~60 seconds after blockhash was fetched
- Final check: verify token balance changed as expected
有关完整的 Solana 交易生命周期,请参阅 。
references/transaction_lifecycle.md- 提交时使用 ,以捕获明显的错误
skipPreflight: False - 每 2 秒轮询一次 ,最长持续 60 秒
getSignatureStatuses - 如果未确认:使用新的 blockhash 重建交易并重试(最多 3 次)
- Blockhash 过期:交易在获取 blockhash 后约 60 秒过期
- 最终检查:验证代币余额是否按预期发生变化
Error Handling
错误处理
| Error | Cause | Recovery |
|---|---|---|
| Price moved beyond slippageBps | Increase slippage or retry |
| Not enough input token or SOL for fees | Check balance before quoting |
| Blockhash too old | Rebuild with fresh blockhash |
| Various — check logs | Parse simulation logs for root cause |
| Route uses too many accounts | Set |
| HTTP 429 | Rate limited | Back off and retry with exponential delay |
HTTP 400 | No liquidity path exists | Check token mints are correct, try larger slippage |
| 错误 | 原因 | 恢复方式 |
|---|---|---|
| 价格变动超出 | 提高滑点或重试 |
| 输入代币或用于支付费用的 SOL 不足 | 报价前检查余额 |
| Blockhash 过旧 | 使用新的 blockhash 重建交易 |
| 多种原因——检查日志 | 解析模拟日志以找出根本原因 |
| 路径使用的账户过多 | 将 |
| HTTP 429 | 受到速率限制 | 指数退避后重试 |
HTTP 400 | 不存在流动性路径 | 检查代币 mint 是否正确,尝试更大的滑点 |
Safety Requirements
安全要求
These are non-negotiable requirements for any execution code.
- ALWAYS show quote details (amounts, price impact, route) before execution
- ALWAYS require explicit user confirmation — never auto-execute
- Default to simulation mode — do not sign or submit unless explicitly enabled
- Never store or log private keys — load from env vars, use immediately, discard
- Never use 100% slippage — this is a common scam/exploit vector
- Verify token addresses — confirm mints match expected tokens before swapping
- Check price impact — warn if >2%, block if >10% unless user overrides
- Maintain SOL reserve — keep 0.05 SOL minimum for rent and future fees
See for the complete pre/during/post execution checklist.
references/safety_checklist.md这些是任何执行代码都必须满足的不可协商要求。
- 始终展示报价详情(金额、价格影响和路径),然后再执行
- 始终要求用户明确确认——绝不自动执行
- 默认使用模拟模式——除非明确启用,否则不得签名或提交
- 绝不存储或记录私钥——从环境变量加载,使用后立即丢弃
- 绝不使用 100% 滑点——这是常见的诈骗和漏洞利用路径
- 验证代币地址——兑换前确认 mint 与预期代币一致
- 检查价格影响——超过 2% 时发出警告,超过 10% 时阻止执行,除非用户明确覆盖
- 保留 SOL 储备——至少保留 0.05 SOL,用于 rent 和未来费用
有关完整的执行前、执行中和执行后验证清单,请参阅 。
references/safety_checklist.mdIntegration with Other Skills
与其他 Skill 的集成
| Skill | Integration |
|---|---|
| Estimate optimal slippageBps based on token liquidity profile |
| Verify pool depth supports trade size before quoting |
| Calculate trade amount based on risk parameters |
| Enforce portfolio-level exposure limits before execution |
| Underlying API documentation for Jupiter endpoints |
| Priority fee estimation and transaction monitoring |
| Skill | 集成方式 |
|---|---|
| 根据代币流动性特征估算最佳 |
| 报价前验证池深度足以支持交易规模 |
| 根据风险参数计算交易金额 |
| 执行前实施投资组合层面的风险敞口限制 |
| Jupiter 端点的底层 API 文档 |
| 优先费估算和交易监控 |
Files
文件
References
引用
- — Complete Jupiter v6 API parameter and response reference
references/jupiter_api.md - — Solana transaction lifecycle, priority fees, retry strategies
references/transaction_lifecycle.md - — Pre/during/post execution verification checklist
references/safety_checklist.md
- — 完整的 Jupiter v6 API 参数和响应参考
references/jupiter_api.md - — Solana 交易生命周期、优先费和重试策略
references/transaction_lifecycle.md - — 执行前、执行中和执行后的验证清单
references/safety_checklist.md
Scripts
脚本
- — Fetch and display Jupiter swap quotes with route analysis
scripts/get_quote.py - — Build and simulate swap transactions without submitting
scripts/simulate_swap.py
- — 获取并展示 Jupiter 兑换报价及路径分析
scripts/get_quote.py - — 构建并模拟兑换交易,但不提交
scripts/simulate_swap.py