简易计算UniswapV2的代币价格 / 学习智能合约#67

in STEEM CN/中文8 days ago

uniswap.jpg
https://app.uniswap.org/swap

简易计算UniswapV2的代币价格,这算是一个补充吧。以前虽也看过V2的合约,一般也用不着自己去求。这次是要集成$Slime的充值,需要计算一下价格,就找来资料试着计算下。

UniswapV2主要使用了 RouterV2 合约的两个方法,把它写成ABI,如下:

const routerAbi = [
      "function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)",
      "function getAmountsIn(uint amountOut, address[] memory path) public view returns (uint[] memory amounts)" 
    ]

以第一个函数getAmountsOut为例,amountIn 表示卖出 token 数量,path 表示交易路径,比如你要卖出 TokenA,换成 ETH,那么最简单的交易路径就是 TokenA -> WETH, 返回值 amounts,表示能获得的目标 WETH 数量。所以 getAmountsOut 这个函数最终表达的意思就是:用某个数量的TokenA,能换到多少数量的TokenB。

这里我们需要用一定量的$Slime换成WETH,然后再相除就可求出 $Slime/WETH的价格,代码如下:

import { ethers } from 'ethers'

//Base网络配置
const base_url = "https://mainnet.base.org"
const routerAbi = [
      "function getAmountsIn(uint amountOut, address[] memory path) public view returns (uint[] memory amounts)",
      "function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)"
    ]
const slimeCon = '0x68503A15efD0D2F81D185a07d60Ed9Ac2a66B59e'
const WETH = '0x4200000000000000000000000000000000000006'
const uniswapRouter = '0x4752ba5DBc23f44D87826276BF6Fd6b1C372aD24'
const provider = new ethers.JsonRpcProvider(base_url)
const routerContract = new ethers.Contract(uniswapRouter, routerAbi, provider) 

async function getSlimePrice(){
  let setAmount = ethers.parseEther("28800")  //假设卖出28800个slime币
  let amountOuts = await routerContract.getAmountsOut(setAmount, [slimeCon, WETH])
  let amountEthOut = ethers.formatEther(amountOuts[1])
  console.log(896,setAmount, amountEthOut)  
  //28800.0  0.001115090084330875
  // 最后价格
  let price_slime_eth = amountEthOut / 28800 
}

得到slime/eth价格后再乘以以太的美元价格($3111.78),就得出$slime的美元价格:0.00012048