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
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;
Commented Mar 3, 2021 at 16:59 -
1Hah I was still editing my answer when you commented. Thanks for the tip.– Cyb0rgCommented Mar 3, 2021 at 17:00
-
2You'll get an explicit type conversion error with the above as
pair.token1
should bepair.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