ethereum - 使用智能合约功能从 Uniswap 获取货币对价格

标签 ethereum solidity smartcontracts remix

我对 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
   }
   
}

但是当我尝试在 Remix 上运行 getTokenPrice 时,它会返回以下错误消息:

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 中部署合约时,它会部署到本地网络。 (默认情况下。例如,如果您注入(inject)生产 Infura 提供程序,您也可以更改它并部署到主网。)

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


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

或者您可以在公共(public)测试网上找到另一个 Uniswap 对(众所周知的是 Rinkeby、Ropsten、Goerli 和 Kovan),并将您的合约部署在同一个测试网上。不要忘记更改传递给 getTokenPrice() 函数的 uniswap 对的测试网地址。

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

关于ethereum - 使用智能合约功能从 Uniswap 获取货币对价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67419852/

相关文章:

ethereum - uniswap 低级交换调用

solidity - 如何在NFT智能合约中编写销毁函数?

solidity - 如何使用松露控制台

storage - 智能合约在区 block 链中的位置(以太坊或 super 账本)

ethereum - Solidity 函数未返回预期数据

ethereum - Remix Ethereum 合约去哪儿了?

node.js - Solidity:ParserError:预期的编译指示、导入指令或合约/interface/library 定义

node.js - 是什么导致 web3js 测试代码中出现 MaxListenersExceededWarning 警告

max - 有没有办法增加Solana链上程序构建的计算单元

c# - Poloniex C# API - 获取交易