0
votes

I am trying to get the price of a pair on UniswapV2: This is my code:

pragma solidity ^0.5.1;

import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
import './IERC20.sol';


contract Uniswap {

   // calculate price based on pair reserves
   function getTokenPrice(address pairAddress, uint amount) public view 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
   }
    
}

I manually imported the openzeppelin IERC20 interface and put as compiler version 0.5.1, because the current version of uniswap v2 periphery is 0.5.1

But I have the following error for the line IERC20 token1 = IERC20(pair.token1);:

Explicit type conversion not allowed from "function () view external returns (address)" to "contract IERC20". IERC20 token1 = IERC20(pair.token1); ^-----------------^

Any idea on how to solve that? thanks!

1

1 Answers

0
votes

The IUniswapV2Pair interface defines a token1() function - not token1 property.

Their contract then uses the fact, that signature of the property is the same as signature of the function, so that it doesn't need to implement the function (as long as it has the public property with the same name).

But when an external contract (such as yours) uses the interface to call functions, it needs to follow it exactly.


So you can simply replace

IERC20 token1 = IERC20(pair.token1); // original code

to

IERC20 token1 = IERC20(pair.token1()); // function `token1()`