我是靠谱客的博主 名字长了才好记,这篇文章主要介绍用ts+viem如何获取uniswap v3池子的价格,现在分享给大家,希望可以做个参考。

在 TypeScript 中使用 viem 获取 Uniswap V3 池子的价格,你需要调用 Uniswap V3 池合约(IUniswapV3Pool)的 slot0 方法,该方法返回当前的价格数据,包括 sqrtPriceX96。然后,你可以将其转换为实际的 Token 价格。

步骤

  1. 安装依赖
npm install viem

2. 导入 viem 并连接以太坊 RPC

import { createPublicClient, http, parseUnits } from 'viem';
import { mainnet } from 'viem/chains';

const client = createPublicClient({
  chain: mainnet,
  transport: http('https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY'), // 你可以换成 Alchemy 或其他 RPC
});

3. 定义 Uniswap V3 池的合约 ABI

const uniswapV3PoolABI = [
  {
    "inputs": [],
    "name": "slot0",
    "outputs": [
      { "internalType": "uint160", "name": "sqrtPriceX96", "type": "uint160" },
      { "internalType": "int24", "name": "tick", "type": "int24" },
      { "internalType": "uint16", "name": "observationIndex", "type": "uint16" },
      { "internalType": "uint16", "name": "observationCardinality", "type": "uint16" },
      { "internalType": "uint16", "name": "observationCardinalityNext", "type": "uint16" },
      { "internalType": "uint8", "name": "feeProtocol", "type": "uint8" },
      { "internalType": "bool", "name": "unlocked", "type": "bool" }
    ],
    "stateMutability": "view",
    "type": "function"
  }
];

4. 获取池子的 sqrtPriceX96 并转换为价格

import { Address, parseUnits, formatUnits } from 'viem';

async function getUniswapV3PoolPrice(poolAddress: Address, token0Decimals: number, token1Decimals: number) {
  const { sqrtPriceX96 } = await client.readContract({
    address: poolAddress,
    abi: uniswapV3PoolABI,
    functionName: 'slot0',
  });

  // 计算价格
  const price = (Number(sqrtPriceX96) ** 2) / (2 ** 192);
  const adjustedPrice = price * (10 ** (token1Decimals - token0Decimals));

  console.log(`Uniswap V3 池子价格: ${adjustedPrice}`);
  return adjustedPrice;
}

// 以 WETH/USDC (0.05% fee) 池子为例
const WETH_USDC_POOL = '0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640'; // Uniswap V3 WETH/USDC 0.05% 池子地址
getUniswapV3PoolPrice(WETH_USDC_POOL, 18, 6);

解释

  • slot0 返回 sqrtPriceX96,这是 √(价格) * 2^96
  • 计算 sqrtPriceX96^2 / 2^192 得到 token0/token1 价格
  • 由于代币可能有不同的小数位数,我们需要调整精度 10 ** (token1Decimals - token0Decimals)

这样,你就可以获取 Uniswap V3 池子的价格! 🚀

最后

以上就是名字长了才好记最近收集整理的关于用ts+viem如何获取uniswap v3池子的价格的全部内容,更多相关用ts+viem如何获取uniswap内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(38)

评论列表共有 0 条评论

立即
投稿
返回
顶部