3

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?

1 Answer 1

6

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
   }
4
  • To improve precision, multiply before dividing. return (amount * res0) / res1; Commented Mar 3, 2021 at 16:59
  • 1
    Hah I was still editing my answer when you commented. Thanks for the tip.
    – Cyb0rg
    Commented Mar 3, 2021 at 17:00
  • 2
    You'll get an explicit type conversion error with the above as pair.token1 should be pair.token1(). Otherwise it worked great though! Commented Jun 3, 2021 at 13:23
  • @Stakedex.io Why did you multiple it with token1.decimals() when the returned values are already in wei? Commented Nov 14, 2022 at 20:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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