I'm trying to create a function that takes a token address as the parameter and returns the price of the token. I saw another post that mentioned the Uniswap SDK, but that used javascript. I'm wondering is there anyway to get the token price using solidity?


You can do this with uniswap if you know the pair address. You will need to import IUniswapV2Pair.sol.

You would also need import ERC20.sol but better to use an interface like IERC20.sol or you can make your own interface but it will need this:

 * @dev Returns the decimals.
function decimals() external view returns (uint256);

And the solidity function:

   // 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
  • To improve precision, multiply before dividing. return (amount * res0) / res1; Mar 3 at 16:59
  • 1
    Hah I was still editing my answer when you commented. Thanks for the tip. Mar 3 at 17:00
  • 1
    You'll get an explicit type conversion error with the above as pair.token1 should be pair.token1(). Otherwise it worked great though! Jun 3 at 13:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.