使用智能合约功能从 Uniswap 获取配对价格

Fetch pair price from Uniswap using smart contract function

我对 Solidity 比较陌生,我正在尝试使用以下合约获取一对的价格:

contract Uniswap {


    constructor () public payable {
    }
   
    function getBalance() public view returns (uint) {
        return address(this).balance;    
    }
   
   
   // calculate price based on pair reserves
   function getTokenPrice(address pairAddress, uint amount) public payable returns(uint)
   {
    IUniswapV2Pair pair = IUniswapV2Pair(pairAddress);
    IERC20 token1 = IERC20(pair.token1());
   
   
    (uint Res0, uint Res1,) = pair.getReserves();

    // decimals
    uint res0 = Res0*(10**token1.decimals());
    return((amount*res0)/Res1); // return amount of token0 needed to buy token1
   }
   
}

但是当我尝试 运行 混音时 getTokenPrice 它 returns 我收到以下错误消息:

The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.

知道为什么吗?我正在尝试获取 ETH/USDT 的价格,因此使用此网站 (https://v2.info.uniswap.org/pair/0x0d4a11d5eeaac28ec3f61d100daf4d40471f1852) 并在 URL 末尾使用配对地址。感谢您的帮助!

当您在 Remix 中部署合约时,它会部署到本地网络。 (默认情况下。您可以更改它并部署到主网,例如,如果您注入生产 Infura 提供程序。)

本地网络上不存在 Uniswap 配对合约 0x0d4a11...


最简单的解决方案是在主网上部署您的合约(0x0d4a11... Uniswap 对合约存在)。

或者您可以在 public 测试网上找到另一个 Uniswap 对(著名的有 Rinkeby、Ropsten、Goerli 和 Kovan),然后在同一个测试网上部署您的合约。不要忘记更改传递给 getTokenPrice() 函数的 uniswap 对的测试网地址。

或者您可以部署 Uniswap 对合约及其所有依赖项并更改依赖项地址(这需要大量工作——我猜它依赖于 Uniswap 路由器合约,即该对的实际代币合约,也许他们依赖于其他一些合同,...)到您的本地网络。从这里开始是一样的——将你的合约部署到本地网络,并使用正确的地址对调用 getTokenPrice()