集成指南
查询价格
如何获取代币价格和交换报价
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
如何获取代币价格和交换报价
const params = new URLSearchParams({
tokenIn: '0xTokenA',
tokenOut: '0xTokenB',
amountIn: '1000000000000000000', // 1 个代币
tradeType: '0'
});
const res = await fetch(`https://dex.kasplex.org/swap-api/api/v1/quote?${params}`);
const quote = await res.json();
console.log(`价格:1 TokenA = ${quote.executionPrice} TokenB`);
console.log(`价格影响:${quote.priceImpact}%`);
// 单个代币价格
const res = await fetch('https://dex.kasplex.org/swap-api/api/v1/price/0xTokenAddress');
// 交易对价格
const res = await fetch('https://dex.kasplex.org/swap-api/api/v1/price/pair/0xToken0/0xToken1');
const PAIR_ABI = [
'function getReserves() view returns (uint112, uint112, uint32)',
'function token0() view returns (address)'
];
const pair = new ethers.Contract(pairAddress, PAIR_ABI, provider);
const [reserve0, reserve1] = await pair.getReserves();
const token0 = await pair.token0();
// token0 以 token1 计价的价格
const price = Number(reserve1) / Number(reserve0);
const POOL_ABI = [
'function slot0() view returns (uint160, int24, uint16, uint16, uint16, uint8, bool)'
];
const pool = new ethers.Contract(poolAddress, POOL_ABI, provider);
const [sqrtPriceX96, tick] = await pool.slot0();
// 将 sqrtPriceX96 转换为价格
const price = (Number(sqrtPriceX96) / 2 ** 96) ** 2;
// 如果代币精度不同,需要调整
const adjustedPrice = price * (10 ** (decimals0 - decimals1));
const res = await fetch(
'https://dex.kasplex.org/swap-api/api/v1/price/history/0xPoolAddress?limit=100'
);
| 方法 | 精度 | 延迟 | 信任模型 | 最适合 |
|---|---|---|---|---|
| 报价 API | 最高(考虑路由) | ~100ms | 中心化 API | 交换界面 |
| 价格 API | 高 | ~50ms | 中心化 API | 仪表盘 |
| 链上 V2 | 池级别 | ~2s(RPC) | 无需信任 | 预言机 |
| 链上 V3 | 池级别 | ~2s(RPC) | 无需信任 | 高级分析 |