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

# 查询价格

> 如何获取代币价格和交换报价

# 查询价格

在 Kroko DEX 上有多种方式查询代币价格，具体取决于你的使用场景。

## 方法 1：报价 API（推荐）

获取价格最准确的方式是请求交换报价。这会考虑所有可用路由，并给出实际执行价格。

```typescript theme={null}
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}%`);
```

**最适合：** 实时交换定价，向用户展示将收到的数量。

<Warning>
  执行价格会因价格影响随交易规模变化。如需参考价格，请使用较小的金额。
</Warning>

## 方法 2：价格 API

无需指定金额即可直接获取价格：

```typescript theme={null}
// 单个代币价格
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');
```

**最适合：** 仪表盘展示、投资组合估值。

## 方法 3：链上查询 (V2)

直接读取 V2 池的储备量：

```typescript theme={null}
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);
```

**最适合：** 无需信任的链上价格读取、预言机类用例。

## 方法 4：链上查询 (V3)

从 V3 池读取当前价格：

```typescript theme={null}
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));
```

**最适合：** V3 专用价格数据、tick 级精度。

## 历史价格

获取历史 K 线数据：

```typescript theme={null}
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） | 无需信任    | 高级分析 |
