You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Uniswap V3创建SwapToken/wETH池:sqrtPriceX96计算及代码检查

Uniswap V3 sqrtPriceX96 计算方案与代码实现

核心逻辑

Uniswap V3 的 sqrtPriceX96 是代币对价格的平方根乘以 2^96,其中价格定义为「每单位 token0 可兑换的 token1 数量」(即 token1 / token0)。计算时必须注意:

  • 代币小数位数的转换(所有数值需基于最小单位计算)
  • 用 BigInt 处理大数,避免 JavaScript 数字精度丢失

针对你的设定:100 SWAP ↔ 0.1 WETH,假设两者均为 18 位小数,计算核心是先得出「1 SWAP 可兑换 0.001 WETH」,再基于此计算平方根并放大 2^96 倍。

JavaScript 计算代码

高精度实现(推荐)

用 BigInt 平方根迭代法避免精度丢失:

// 辅助函数:计算 BigInt 的整数平方根
function sqrtBigInt(n) {
  if (n < 0n) throw new Error('负数无平方根');
  if (n === 0n || n === 1n) return n;
  let low = 1n;
  let high = n;
  let result;
  while (low <= high) {
    const mid = (low + high) / 2n;
    const midSquared = mid * mid;
    if (midSquared === n) return mid;
    if (midSquared < n) {
      low = mid + 1n;
      result = mid;
    } else {
      high = mid - 1n;
    }
  }
  return result;
}

// 代币小数位数(根据你的实际代币调整)
const swapDecimals = 18;
const wethDecimals = 18;

// 转换为最小单位数量:100 SWAP = 100 * 10^18;0.1 WETH = 1e17
const amountSwap = 100n * (10n ** BigInt(swapDecimals));
const amountWeth = 100000000000000000n;

// 计算 sqrtPriceX96 = sqrt(amountWeth / amountSwap) * 2^96
const sqrtAmountWeth = sqrtBigInt(amountWeth);
const sqrtAmountSwap = sqrtBigInt(amountSwap);
const Q96 = 2n ** 96n;

const sqrtPriceX96 = (sqrtAmountWeth * Q96) / sqrtAmountSwap;

console.log("sqrtPriceX96:", sqrtPriceX96.toString());

简易实现(适合快速验证)

如果对精度要求不高,可借助 Math.sqrt 快速计算:

const swapDecimals = 18;
const wethDecimals = 18;

// 最小单位数量
const amountSwap = 100n * (10n ** BigInt(swapDecimals));
const amountWeth = 100000000000000000n;

// 计算价格比值(token1/token0)
const priceRatio = Number(amountWeth) / Number(amountSwap);
const sqrtPrice = Math.sqrt(priceRatio);

// 2^96 的数值
const Q96 = 2n ** 96n;
const sqrtPriceX96 = BigInt(Math.floor(sqrtPrice * Number(Q96)));

console.log("sqrtPriceX96:", sqrtPriceX96.toString());

常见代码问题修正

如果你的现有代码无法得到正确结果,大概率是以下问题:

  • 未转换最小单位:直接使用 100、0.1 这类人类可读数值,而非代币的最小单位(需乘以 10^decimals)
  • 价格比例搞反:用了 SWAP/WETH 而非 WETH/SWAP 的比值
  • 精度丢失:用普通 Number 类型处理大数,导致溢出或精度下降(必须用 BigInt)
  • Q96 计算错误:直接用数字计算 2^96 会溢出,需用 2n ** 96n 生成 BigInt

内容的提问来源于stack exchange,提问作者emtothed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 10:32:03